package com.eorchis.module.trainingplan.ui.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.eorchis.constants.DeptConstants;
import com.eorchis.constants.RoleConstants;
import com.eorchis.core.service.IBaseService;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.ResultJson;
import com.eorchis.module.classplanapply.service.IClassPlanApplyService;
import com.eorchis.module.classplanapply.ui.commond.ClassPlanApplyQueryCommond;
import com.eorchis.module.classplanapply.ui.commond.ClassPlanApplyValidCommond;
import com.eorchis.module.classuser.domain.ClassUserSheet;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.remind.domain.Remind;
import com.eorchis.module.remind.service.IRemindService;
import com.eorchis.module.security.cas.domain.Role;
import com.eorchis.module.trainingclass.domain.TrainingClass;
import com.eorchis.module.trainingclass.service.ITrainingClassService;
import com.eorchis.module.trainingclass.ui.commond.TrainingClassValidCommond;
import com.eorchis.module.trainingplan.domain.ClassPlanApplyQueryBean;
import com.eorchis.module.trainingplan.domain.TrainingPlan;
import com.eorchis.module.trainingplan.domain.TrainingPlanApplyContrast;
import com.eorchis.module.trainingplan.domain.TrainingPlanBean;
import com.eorchis.module.trainingplan.domain.TrainingPlanExport;
import com.eorchis.module.trainingplan.domain.yearlyPlanExport;
import com.eorchis.module.trainingplan.service.ITrainingPlanService;
import com.eorchis.module.trainingplan.ui.commond.TrainingPlanFileValidCommond;
import com.eorchis.module.trainingplan.ui.commond.TrainingPlanFileZZBValidCommond;
import com.eorchis.module.trainingplan.ui.commond.TrainingPlanQueryCommond;
import com.eorchis.module.trainingplan.ui.commond.TrainingPlanValidCommond;
import com.eorchis.module.util.JsonToT;
import com.eorchis.module.util.StringUtil;
import com.eorchis.module.util.ZipUtil;
import com.eorchis.util.excel.ExcelImportResult;
import com.eorchis.utils.JSONUtils;
import com.eorchis.utils.excelutil.ExcelIO;
import com.eorchis.utils.excelutil.ExcelIOFactory;
import com.eorchis.utils.excelutil.export.bo.Sheet;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: TrainingPlanController<br>
 * Description: 培训计划管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * 
 * @author RongSL
 * @createDate 2016-07-12
 * @version $Revision$
 */
@Controller("trainingPlanController")
@RequestMapping(value = TrainingPlanController.MODULE_PATH)
public class TrainingPlanController extends AbstractBaseController<TrainingPlanValidCommond, TrainingPlanQueryCommond> {
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/trainingplan";
	// 培训计划接口
	@Autowired
	@Qualifier("com.eorchis.module.trainingplan.service.impl.TrainingPlanServiceImpl")
	private ITrainingPlanService trainingPlanService;

	// 提醒表接口
	@Resource(name = "com.eorchis.module.remind.service.impl.RemindServiceImpl")
	private IRemindService remindService;

	// 培训班信息接口
	@Autowired
	@Qualifier("com.eorchis.module.trainingclass.service.impl.TrainingClassServiceImpl")
	private ITrainingClassService trainingClassService;

	// 班级计划报名接口
	@Autowired
	@Qualifier("com.eorchis.module.classplanapply.service.impl.ClassPlanApplyServiceImpl")
	private IClassPlanApplyService classPlanApplyService;

	public IBaseService getService() {
		return trainingPlanService;
	}

	public String getModulePath() {
		return MODULE_PATH;
	}

	public String getPageBasePath() {
		return "/portal/project/module/trainingplan";
	}

	/**
	 * 导出培训计划列表
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 */
	@RequestMapping("/exportTrainingPlanListForExcel")
	public void exportTrainingPlanListForExcel(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		// List<?> exportResults =
		// trainingPlanService.findAllList(queryCommond);
		Role role = (Role) request.getSession().getAttribute("currentRole");
		List<TrainingPlanValidCommond> list = null;
		Department dep = (Department) request.getSession().getAttribute("currentScope");
		if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_BW_ADMIN)) {
			// 部委管理员列表
			queryCommond.setSearchUndertakeID(dep.getDeptID());
			list = trainingPlanService.findPlanListBW(queryCommond);
		} else if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_ZZB_ADMIN)) {
			// 中组部管理员列表
			// if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchAuditState())){
			// queryCommond.setSearchAuditState(TrainingPlan.AUDITSTATE_W);
			// }
			list = trainingPlanService.findPlanList(queryCommond);
		} else {
			// 地方管理员列表
			queryCommond.setSearchDeptId(dep.getDeptID());
			list = trainingPlanService.findPlanListDF(queryCommond);
		}

		TrainingPlanExport tpe = new TrainingPlanExport();
		tpe.setTrainingPlan(list);

		ClassUserSheet classUserSheet = new ClassUserSheet();
		classUserSheet.setExportObject(tpe);
		classUserSheet.setExprotFormatName("TrainingPlanExcelConfig");
		classUserSheet.setSheetName("培训计划列表");

		Sheet[] sheetArray = new Sheet[] { classUserSheet };// 导出Excel的Sheet集合
		ExcelIO excelio = ExcelIOFactory.getExcelIO();// Excel导出工具
		String title = "培训计划列表";
		response.setContentType("application/msexcel;charset=ISO8859-1");
		response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(title, "UTF-8") + ".xls");
		OutputStream out = response.getOutputStream();
		excelio.exportExcel(out, "resumeExportStyle", sheetArray, false);
	}

	/**
	 * 导出年度培训计划名额分配表
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 */
	@RequestMapping("/exportExportYearPlanForExcel")
	public void exportExportYearPlanForExcel(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		try {
			// 第一步，创建一个webbook，对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
			HSSFSheet sheet = wb.createSheet("年度培训计划名额分配表");
			sheet.setDefaultRowHeight((short) 432);// 默认单元格高度
			// 设置字体样式
			HSSFFont font = wb.createFont();
			font.setFontName("黑体");
			font.setFontHeightInPoints((short) 18);// 设置字体大小
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示

			HSSFFont font2 = wb.createFont();
			font2.setFontName("楷体");
			font2.setFontHeightInPoints((short) 13);// 设置字体大小

			HSSFFont font3 = wb.createFont();// 题组样式
			font3.setFontName("微软雅黑");
			font3.setFontHeightInPoints((short) 15);// 设置字体大小

			HSSFFont font4 = wb.createFont();// 题组样式
			font4.setFontName("微软雅黑");
			font4.setFontHeightInPoints((short) 25);// 设置字体大小

			// 设置单元格样式
			HSSFCellStyle style0 = wb.createCellStyle();// 标题样式
			style0.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中对齐
			style0.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style0.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style0.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style0.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style0.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style0.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style0.setFillForegroundColor(HSSFColor.WHITE.index);// 单元格背景色
			style0.setFont(font);
			HSSFCellStyle style5 = wb.createCellStyle();// 标题样式
			style5.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
			style5.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style5.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style5.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style5.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style5.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style5.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style5.setFillForegroundColor(HSSFColor.WHITE.index);// 单元格背景色
			style5.setFont(font4);
			HSSFCellStyle style1 = wb.createCellStyle();// 单选样式
			style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
			style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style1.setFillForegroundColor(HSSFColor.LIME.index);// 单元格背景色
			style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style1.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style1.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style1.setFont(font2);
			HSSFCellStyle style2 = wb.createCellStyle();// 多选样式
			style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
			style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style2.setFillForegroundColor(HSSFColor.CORNFLOWER_BLUE.index);// 单元格背景色
			style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style2.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style2.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style2.setFont(font2);
			HSSFCellStyle style3 = wb.createCellStyle();
			style3.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
			style3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			// style3.setFillForegroundColor(HSSFColor.GOLD.index);// 单元格背景色
			style3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style3.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style3.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style3.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style3.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style3.setFont(font2);

			HSSFCellStyle style4 = wb.createCellStyle();
			style4.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
			style4.setWrapText(true);
			style4.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style4.setFillForegroundColor(HSSFColor.SKY_BLUE.index);// 单元格背景色
			style4.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style4.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style4.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style4.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style4.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style4.setFont(font3);

			HSSFRow row;
			HSSFCell cell;
			int rows = 0;// 当前行
			int column = 0;// 当前列
			int width = 0;// 宽度
			List<String> cityCount = new ArrayList<String>();// 计划总市级人数
			List<String> countyCount = new ArrayList<String>();// 计划总县级人数
			List<String> count = new ArrayList<String>();// 计划总人数
			// 查询年度计划列表
			List<yearlyPlanExport> ype = trainingPlanService.ExportYearPlan(queryCommond);

			if (PropertyUtil.objectNotEmpty(ype) && PropertyUtil.objectNotEmpty(ype.get(0))) {
				for (int i = 0; i < 40; i++) {
					sheet.createRow(i);
				}

				// 写入标题
				row = sheet.getRow(rows);
				sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, ype.size()));
				cell = row.createCell(column);
				cell.setCellValue("学员名额分配表");
				cell.setCellStyle(style5);
				rows += 3;

				// 写入地区各部门
				cell = sheet.getRow(rows).createCell(column);
				cell.setCellValue("计划编号");
				cell.setCellStyle(style4);
				rows++;
				cell = sheet.getRow(rows).createCell(column);
				cell.setCellValue("级别");
				cell.setCellStyle(style4);
				rows++;
				for (yearlyPlanExport yp : ype) {
					if (yp.getDeptNames().length==yearlyPlanExport.deptCount) {
						for (int i = 0; i < yp.getDeptNames().length; i++) {
							cell = sheet.getRow(rows).createCell(column);
							cell.setCellValue(yp.getDeptNames()[i]);
							cell.setCellStyle(style1);
							if (yp.getDeptNames()[i].length() > width) {
								width = yp.getDeptNames()[i].length();
							}
							rows++;
						}
						break;
					}
				}

				// 写入名额分配信息
				rows = 0;
				column++;
				for (yearlyPlanExport y : ype) {
					Integer city = 0;
					Integer county = 0;
					rows = 3;
					if (y.getCityPlanCountSum() != 0 && y.getCountyPlanCountSum() != 0) {
						sheet.addMergedRegion(new CellRangeAddress(rows, rows, column, column + 1));
						cell = sheet.getRow(rows).createCell(column);
						cell.setCellValue(y.getApplyNum());
						cell.setCellStyle(style4);
						rows++;
						cell = sheet.getRow(rows).createCell(column);
						cell.setCellValue("市");
						cell.setCellStyle(style4);
						cell = sheet.getRow(rows).createCell(column + 1);
						cell.setCellValue("县");
						cell.setCellStyle(style4);
						rows++;
						for (String s : y.getCityPlanCounts()) {
							cell = sheet.getRow(rows).createCell(column);
							cell.setCellValue(s);
							cell.setCellStyle(style1);
							city += Integer.valueOf(s);
							rows++;
						}
						rows = 5;
						for (String s : y.getCountyPlanCounts()) {
							cell = sheet.getRow(rows).createCell(column + 1);
							cell.setCellValue(s);
							cell.setCellStyle(style1);
							county += Integer.valueOf(s);
							rows++;
						}
						column += 2;
					} else if (y.getCityPlanCountSum() != 0) {
						cell = sheet.getRow(rows).createCell(column);
						cell.setCellValue(y.getApplyNum());
						cell.setCellStyle(style4);
						rows++;
						cell = sheet.getRow(rows).createCell(column);
						cell.setCellValue("市");
						cell.setCellStyle(style4);
						rows++;
						for (String s : y.getCityPlanCounts()) {
							cell = sheet.getRow(rows).createCell(column);
							cell.setCellValue(s);
							cell.setCellStyle(style1);
							city += Integer.valueOf(s);
							rows++;
						}
						column++;
					} else if (y.getCountyPlanCountSum() != 0) {
						cell = sheet.getRow(rows).createCell(column);
						cell.setCellValue(y.getApplyNum());
						cell.setCellStyle(style4);
						rows++;
						cell = sheet.getRow(rows).createCell(column);
						cell.setCellValue("县");
						cell.setCellStyle(style4);
						rows++;
						for (String s : y.getCountyPlanCounts()) {
							cell = sheet.getRow(rows).createCell(column);
							cell.setCellValue(s);
							cell.setCellStyle(style1);
							county += Integer.valueOf(s);
							rows++;
						}
						column++;
					}
					cityCount.add(city + "");
					countyCount.add(county + "");
					count.add(city + county + "");
				}

				// 写入各地选调总人数
				rows = 3;
				sheet.addMergedRegion(new CellRangeAddress(rows, rows, column, column + 2));
				cell = sheet.getRow(rows).createCell(column);
				cell.setCellValue("各地方选调总人数");
				cell.setCellStyle(style4);
				rows++;
				cell = sheet.getRow(rows).createCell(column);
				cell.setCellValue("市");
				cell.setCellStyle(style4);
				cell = sheet.getRow(rows).createCell(column + 1);
				cell.setCellValue("县");
				cell.setCellStyle(style4);
				cell = sheet.getRow(rows).createCell(column + 2);
				cell.setCellValue("合计");
				cell.setCellStyle(style4);
				rows++;
				Integer c1 = 0, t1 = 0, s1 = 0;
				for (int i = 0; i < yearlyPlanExport.deptCount; i++) {
					Integer c = 0;
					Integer t = 0;
					Integer s = 0;
					for (yearlyPlanExport y : ype) {
						c += Integer.valueOf(y.getCityPlanCounts()[i]);
						t += Integer.valueOf(y.getCountyPlanCounts()[i]);
						s = c + t;
					}
					cell = sheet.getRow(rows).createCell(column);
					cell.setCellValue(c);
					cell.setCellStyle(style1);
					cell = sheet.getRow(rows).createCell(column + 1);
					cell.setCellValue(t);
					cell.setCellStyle(style1);
					cell = sheet.getRow(rows).createCell(column + 2);
					cell.setCellValue(s);
					cell.setCellStyle(style1);
					rows++;
					c1 += c;
					t1 += t;
					s1 += s;
				}

				// 写入各班总人数
				column = 0;
				sheet.addMergedRegion(new CellRangeAddress(rows, rows + 1, column, column));
				cell = sheet.getRow(rows).createCell(column);
				cell.setCellValue("各班总人数");
				cell.setCellStyle(style4);
				column++;
				for (yearlyPlanExport y : ype) {
					if (y.getCityPlanCountSum() != 0 && y.getCountyPlanCountSum() != 0) {
						cell = sheet.getRow(rows).createCell(column);
						cell.setCellValue(y.getCityPlanCountSum());
						cell.setCellStyle(style4);
						cell = sheet.getRow(rows).createCell(column + 1);
						cell.setCellValue(y.getCountyPlanCountSum());
						cell.setCellStyle(style4);
						sheet.addMergedRegion(new CellRangeAddress(rows + 1, rows + 1, column, column + 1));
						cell = sheet.getRow(rows + 1).createCell(column);
						cell.setCellValue(y.getCountyPlanCountSum() + y.getCityPlanCountSum());
						cell.setCellStyle(style4);
						column += 2;
					} else {
						sheet.addMergedRegion(new CellRangeAddress(rows, rows + 1, column, column));
						cell = sheet.getRow(rows).createCell(column);
						cell.setCellValue(y.getCountyPlanCountSum() + y.getCityPlanCountSum());
						cell.setCellStyle(style4);
						column++;
					}
				}
				// 写入选调总人数&各班总人数
				int q = 0, w = 0, e = 0;
				for (yearlyPlanExport y : ype) {
					q += y.getCityPlanCountSum();
					w += y.getCountyPlanCountSum();
					e += y.getCityPlanCountSum() + y.getCountyPlanCountSum();
				}
				sheet.addMergedRegion(new CellRangeAddress(rows, rows + 1, column, column));
				cell = sheet.getRow(rows).createCell(column);
				cell.setCellValue(q);
				cell.setCellStyle(style4);
				column++;
				sheet.addMergedRegion(new CellRangeAddress(rows, rows + 1, column, column));
				cell = sheet.getRow(rows).createCell(column);
				cell.setCellValue(w);
				cell.setCellStyle(style4);
				column++;
				sheet.addMergedRegion(new CellRangeAddress(rows, rows + 1, column, column));
				cell = sheet.getRow(rows).createCell(column);
				cell.setCellValue(e);
				cell.setCellStyle(style4);

				sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, column));
				sheet.getRow(0).getCell(0).setCellStyle(style5);

				for (int i = 0; i <= column; i++) {
					sheet.getRow(rows).getCell(i).setCellStyle(style4);
				}
				for (int i = 0; i <= column; i++) {
					try {
						sheet.getRow(rows + 1).getCell(i).setCellStyle(style4);
					} catch (Exception e1) {
						sheet.getRow(rows + 1).createCell(i).setCellStyle(style4);
					}
				}
				for (int i = 0; i <= column; i++) {
					try {
						sheet.getRow(3).getCell(i).setCellStyle(style4);
					} catch (Exception e1) {
						sheet.getRow(3).createCell(i).setCellStyle(style4);
					}
				}

				sheet.setColumnWidth(0, width * 256 * 3);
				for (int i = 1; i < column + 1; i++) {
					sheet.setColumnWidth(i, 12 * 256);
				}
				response.reset();
				response.setContentType("application/x-msdownload");
				response.setHeader("Content-Disposition", "attachment; filename=" + new String(("学员名额分配表").getBytes("gb2312"), "ISO-8859-1") + ".xls");
				ServletOutputStream outStream = null;
				outStream = response.getOutputStream();
				wb.write(outStream);
				outStream.close();
			} else {
				response.setCharacterEncoding("GB2312");
				PrintWriter pw = response.getWriter();
				pw.write("<script>alert('暂无数据');window.opener='';window.open('', '_self', '');window.close();</script>");
				pw.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出培训计划详情及名额
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 */
	@RequestMapping("/exportTrainingPlanPlacesForExcel")
	public void exportTrainingPlanPlacesForExcel(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		FileOutputStream fOut = null;
		try {
			// 第一步，创建一个webbook，对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
			HSSFSheet sheet;
			// 设置字体样式
			HSSFFont font = wb.createFont();
			font.setFontName("黑体");
			font.setFontHeightInPoints((short) 18);// 设置字体大小
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示

			HSSFFont font2 = wb.createFont();
			font2.setFontName("楷体");
			font2.setFontHeightInPoints((short) 13);// 设置字体大小

			HSSFFont font3 = wb.createFont();// 题组样式
			font3.setFontName("微软雅黑");
			font3.setFontHeightInPoints((short) 15);// 设置字体大小

			// 设置单元格样式
			HSSFCellStyle style0 = wb.createCellStyle();// 标题样式
			style0.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION); // 居中对齐
			style0.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style0.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style0.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style0.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style0.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style0.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style0.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style0.setFillForegroundColor(HSSFColor.WHITE.index);// 单元格背景色
			style0.setFont(font);
			HSSFCellStyle style1 = wb.createCellStyle();// 单选样式
			style1.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个居中格式
			style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style1.setFillForegroundColor(HSSFColor.LIME.index);// 单元格背景色
			style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style1.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style1.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style1.setFont(font2);
			HSSFCellStyle style2 = wb.createCellStyle();// 多选样式
			style2.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个居中格式
			style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style2.setFillForegroundColor(HSSFColor.CORNFLOWER_BLUE.index);// 单元格背景色
			style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style2.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style2.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style2.setFont(font2);
			HSSFCellStyle style3 = wb.createCellStyle();
			style3.setWrapText(true);
			style3.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个居中格式
			style3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style3.setFillForegroundColor(HSSFColor.GOLD.index);// 单元格背景色
			style3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style3.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style3.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style3.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style3.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style3.setFont(font2);

			HSSFCellStyle style4 = wb.createCellStyle();
			style4.setWrapText(true);
			style4.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
			style4.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			style4.setFillForegroundColor(HSSFColor.SKY_BLUE.index);// 单元格背景色
			style4.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style4.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
			style4.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
			style4.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
			style4.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
			style4.setFont(font3);

			HSSFRow row;
			HSSFCell cell1;
			HSSFCell cell2;
			int rows = 0;// 当前行
			int width = 0;// 宽度

			String serverPath = request.getSession().getServletContext().getRealPath(File.separator);
			// 在服务器端创建文件夹
			serverPath += System.currentTimeMillis() + File.separator;
			File file = new File(serverPath);
			if (!file.exists()) {
				file.mkdir();
			}
			List<String> xlsNames = new ArrayList<String>();

			// 获得待导出的计划id
			Role role = (Role) request.getSession().getAttribute("currentRole");
			List<TrainingPlanValidCommond> list1 = null;
			Department dep = (Department) request.getSession().getAttribute("currentScope");
			if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_BW_ADMIN)) {
				// 部委管理员列表
				Department d = (Department) request.getSession().getAttribute("currentScope");
				if (!d.getDeptID().equals(1 + "")) {
					queryCommond.setSearchUndertakeID(dep.getDeptID());
				}
				list1 = trainingPlanService.findPlanListBW(queryCommond);
			} else if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_ZZB_ADMIN)) {
				// 中组部管理员列表
				// if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchAuditState())){
				// queryCommond.setSearchAuditState(TrainingPlan.AUDITSTATE_W);
				// }
				list1 = trainingPlanService.findPlanList(queryCommond);
			}
			List<String> l = new ArrayList<String>();
			for (TrainingPlanValidCommond t : list1) {
				l.add(t.getPlanId());
			}
			String idss[] = l.toArray(new String[] {});
			queryCommond.setSearchPlanIds(idss);

			if (PropertyUtil.objectNotEmpty(queryCommond.getSearchPlanIds())) {
				for (String id : queryCommond.getSearchPlanIds()) {
					TrainingPlanValidCommond commond = new TrainingPlanValidCommond();
					commond.setPlanId(id);
					commond = trainingPlanService.findTrainingPlan(commond);
					String title = "培训计划详情表";
					String sheetName = "培训计划详情表";
					sheet = wb.createSheet(sheetName);
					sheet.setDefaultRowHeight((short) 432);// 默认单元格高度
					row = sheet.createRow(rows);
					// 编写sheet1标题
					sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
					cell1 = row.createCell(0);
					cell1.setCellValue(title);
					cell1.setCellStyle(style0);
					rows++;

					flag: while (true) {
						row = sheet.createRow(rows);
						cell1 = row.createCell(0);
						cell2 = row.createCell(1);
						switch (rows) {
						case 1:
							cell1.setCellValue("专题名称：");
							cell2.setCellValue(commond.getClassName());
							if (width < StringUtil.stringSize(commond.getClassName())) {
								width = StringUtil.stringSize(commond.getClassName());
							}
							rows++;
							break;
						case 2:
							cell1.setCellValue("计划申请编号：");
							cell2.setCellValue(commond.getApplyNum());
							if (width < StringUtil.stringSize(commond.getApplyNum())) {
								width = StringUtil.stringSize(commond.getApplyNum());
							}
							rows++;
							break;
						case 3:
							cell1.setCellValue("承办部委：");
							cell2.setCellValue(commond.getUndertakeName());
							if (width < StringUtil.stringSize(commond.getUndertakeName())) {
								width = StringUtil.stringSize(commond.getUndertakeName());
							}
							rows++;
							break;
						case 4:
							cell1.setCellValue("合办部委：");
							cell2.setCellValue(commond.getJointName());
							if (width < StringUtil.stringSize(commond.getJointName())) {
								width = StringUtil.stringSize(commond.getJointName());
							}
							rows++;
							break;
						case 5:
							cell1.setCellValue("计划开始时间：");
							String startDate = new SimpleDateFormat("yyyy-MM-dd").format(commond.getStartPlanDate());
							cell2.setCellValue(startDate);
							if (width < StringUtil.stringSize(startDate)) {
								width = StringUtil.stringSize(startDate);
							}
							rows++;
							break;
						case 6:
							cell1.setCellValue("计划结束时间：");
							String endDate = new SimpleDateFormat("yyyy-MM-dd").format(commond.getEndPlanDate());
							cell2.setCellValue(endDate);
							if (width < StringUtil.stringSize(endDate)) {
								width = StringUtil.stringSize(endDate);
							}
							rows++;
							break;
						// case 7:
						// cell1.setCellValue("学制（天）：");
						// cell2.setCellValue(commond.getPlanDay());
						// if (width <
						// StringUtil.stringSize(commond.getPlanDay())) {
						// width = StringUtil.stringSize(commond.getPlanDay());
						// }
						// rows++;
						// break;
						case 7:
							cell1.setCellValue("办班目的：");
							cell2.setCellValue(commond.getClassObjective());
							if (width < StringUtil.stringSize(commond.getClassObjective())) {
								width = StringUtil.stringSize(commond.getClassObjective());
							}
							rows++;
							break;
						case 8:
							cell1.setCellValue("培训内容：");
							cell2.setCellValue(commond.getClassValues());
							if (width < StringUtil.stringSize(commond.getClassValues())) {
								width = StringUtil.stringSize(commond.getClassValues());
							}
							rows++;
							break;
						case 9:
							cell1.setCellValue("调训对象：");
							cell2.setCellValue(commond.getTrainingObject());
							if (width < StringUtil.stringSize(commond.getTrainingObject())) {
								width = StringUtil.stringSize(commond.getTrainingObject());
							}
							rows++;
							break;
						case 10:
							cell1.setCellValue("培训地点：");
							cell2.setCellValue(commond.getTrainingAddress());
							if (width < StringUtil.stringSize(commond.getTrainingAddress())) {
								width = StringUtil.stringSize(commond.getTrainingAddress());
							}
							rows++;
							break;
						case 11:
							cell1.setCellValue("联系人：");
							cell2.setCellValue(commond.getLinkMan());
							if (width < StringUtil.stringSize(commond.getLinkMan())) {
								width = StringUtil.stringSize(commond.getLinkMan());
							}
							rows++;
							break;
						case 12:
							cell1.setCellValue("联系电话：");
							cell2.setCellValue(commond.getLinkMode());
							if (width < StringUtil.stringSize(commond.getLinkMode())) {
								width = StringUtil.stringSize(commond.getLinkMode());
							}
							rows++;
							break;
						case 13:
							cell1.setCellValue("传真：");
							cell2.setCellValue(commond.getFax());
							if (width < StringUtil.stringSize(commond.getFax())) {
								width = StringUtil.stringSize(commond.getFax());
							}
							cell1.setCellStyle(style4);
							cell2.setCellStyle(style3);
							rows++;
							break flag;
						}
						cell1.setCellStyle(style4);
						cell2.setCellStyle(style3);
					}

					sheet.setColumnWidth(0, 7000);
					//第二列最多显示内容数
					if(width>30){
						width=30;
					}
					sheet.setColumnWidth(1, width * 256 * 3);

					// 第二个sheet-培训计划名额表
					ClassPlanApplyQueryCommond query = new ClassPlanApplyQueryCommond();
					query.setSearchClassId(commond.getApplyNum());
					// 过滤企业
					query.setSearchDeptCode("企业");
					List<ClassPlanApplyQueryBean> resultList = trainingPlanService.findClassPlanApplyQueryBeanList(query);
					if (PropertyUtil.objectNotEmpty(resultList)) {
						ClassPlanApplyQueryBean cpa = new ClassPlanApplyQueryBean();
						LinkedList<ClassPlanApplyQueryBean> list = new LinkedList<ClassPlanApplyQueryBean>();
						list.addAll(resultList);
						int cityCount = 0;
						int countyCount = 0;
						for (ClassPlanApplyQueryBean c : resultList) {
							cityCount += c.getCityPlanCount();
							countyCount += c.getCountyPlanCount();
						}
						cpa.setCityPlanCount(cityCount);
						cpa.setCountyPlanCount(countyCount);
						cpa.setPlanCount(cityCount + countyCount);
						cpa.setDeptCode("合计");
						list.addFirst(cpa);
						list.addFirst(null);

						sheet = wb.createSheet("培训计划名额表");
						sheet.setDefaultRowHeight((short) 432);// 默认单元格高度
						rows = 0;
						HSSFCell cell;
						int column = 0;// 当前列

						// 编写标题
						sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
						sheet.setColumnWidth(0, 6000);
						sheet.setColumnWidth(1, 5000);
						sheet.setColumnWidth(2, 5000);
						sheet.setColumnWidth(3, 5000);
						row = sheet.createRow(rows);
						cell = row.createCell(column);
						cell.setCellValue(commond.getClassName() + "培训计划名额表");
						cell.setCellStyle(style0);
						rows++;

						for (ClassPlanApplyQueryBean cp : list) {
							row = sheet.createRow(rows);
							flag: while (true) {
								cell = row.createCell(column);
								switch (column) {
								case 0:
									if (rows == 1) {
										cell.setCellValue("单位名称");
										cell.setCellStyle(style4);
									} else {
										cell.setCellValue(cp.getDeptCode());
										cell.setCellStyle(style3);
									}
									column++;
									break;
								case 1:
									if (rows == 1) {
										cell.setCellValue("计划市级人数");
										cell.setCellStyle(style4);
									} else {
										cell.setCellValue(cp.getCityPlanCount());
										cell.setCellStyle(style3);
									}
									column++;
									break;
								case 2:
									if (rows == 1) {
										cell.setCellValue("计划县级人数");
										cell.setCellStyle(style4);
									} else {
										cell.setCellValue(cp.getCountyPlanCount());
										cell.setCellStyle(style3);
									}
									column++;
									break;
								case 3:
									if (rows == 1) {
										cell.setCellValue("计划总人数");
										cell.setCellStyle(style4);
									} else {
										cell.setCellValue(cp.getPlanCount());
										cell.setCellStyle(style3);
									}
									column = 0;
									break flag;
								}
							}
							rows++;
						}
					}
					rows = 0;
					// 保存到本地
					String xlsName = null;
					// xlsName = new String((serverPath + commond.getApplyNum()
					// + ".xls").getBytes(), "UTF-8");
					if (commond.getPublishState().equals(TrainingPlan.PUBLISHSTATE_Y)) {
						xlsName = new String((serverPath + commond.getUndertakeName() + "-" + commond.getClassName() + ".xls").getBytes(), "UTF-8");
						xlsName = new String((serverPath + commond.getUndertakeName() + "-" + commond.getClassName() + ".xls").getBytes(), "UTF-8");
					} else {
						xlsName = new String((serverPath + commond.getUndertakeName() + "-" + commond.getClassName() + "（讨论稿）.xls").getBytes(), "UTF-8");
						xlsName = new String((serverPath + commond.getUndertakeName() + "-" + commond.getClassName() + "（讨论稿）.xls").getBytes(), "UTF-8");
					}
					File f = new File(xlsName);
					int x = 2;
					// 如果文件已存在，则重新命名
					while (f.exists()) {
						int i = xlsName.lastIndexOf(".");
						xlsName = xlsName.substring(0, i) + x + ".xls";
						f = new File(xlsName);
					}

					fOut = new FileOutputStream(xlsName);
					wb.write(fOut);
					fOut.flush();
					fOut.close();
					xlsNames.add(xlsName);
					int w = wb.getNumberOfSheets();
					for (int i = 0; i < w; i++) {
						wb.removeSheetAt(i);
						i = -1;
						w = wb.getNumberOfSheets();
					}
				}

				File zipfile = new File(serverPath + "培训计划详情及名额.zip");
				// File zipfile = new File(serverPath + "classInfo.zip");
				ZipUtil.zipFiles(xlsNames, zipfile);
				// 弹出下载框供用户下载
				ZipUtil.downFile(response, serverPath, "培训计划详情及名额.zip");
				// ZipUtil.downFile(response, serverPath, "classInfo.zip");
				// 删除生成文件夹，Excel及ZIP
				ZipUtil.deleteExcelPath(new File(serverPath));
			}

			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			resultState.setMessage("导出成功！");
		} catch (Exception e) {
			e.printStackTrace();
			resultState.setState(ResultState.RESULT_STATE_FAIL);
			resultState.setMessage("导出异常，请联系系统管理员！");
		} finally {
			fOut.close();
		}
	}

	/**
	 * 新增培训计划
	 * 
	 * @author RongSL
	 * */
	@RequestMapping("/saveTrainingPlan")
	public void saveTrainingPlan(@ModelAttribute("result") TrainingPlanBean Commond, @ModelAttribute("resultState") ResultState resultState, HttpServletRequest request) {
		try {
			TrainingPlanValidCommond validCommond = new TrainingPlanValidCommond();
			Department dep = (Department) request.getSession().getAttribute("currentScope");
			validCommond.setUndertakeName(dep.getDeptName());
			validCommond.setUndertakeId(dep.getDeptID());
			if (PropertyUtil.objectNotEmpty(Commond.getClassNameNew())) {
				validCommond.setClassName(Commond.getClassNameNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getClassObjectiveNew())) {
				validCommond.setClassObjective(Commond.getClassObjectiveNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getClassValuesNew())) {
				validCommond.setClassValues(Commond.getClassValuesNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getLinkManNew())) {
				validCommond.setLinkMan(Commond.getLinkManNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getLinkModeNew())) {
				validCommond.setLinkMode(Commond.getLinkModeNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getFaxNew())) {
				validCommond.setFax(Commond.getFaxNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getStartPlanDateNewStr())) {
				validCommond.setStartPlanDateStr(Commond.getStartPlanDateNewStr());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getEndPlanDateNewStr())) {
				validCommond.setEndPlanDateStr(Commond.getEndPlanDateNewStr());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getPlanDayNew())) {
				validCommond.setPlanDay(Commond.getPlanDayNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getTrainingAddressNew())) {
				validCommond.setTrainingAddress(Commond.getTrainingAddressNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getTrainingObjectNew())) {
				validCommond.setTrainingObject(Commond.getTrainingObjectNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getJointNameNew())) {
				validCommond.setJointName(Commond.getJointNameNew());
			}
			if (PropertyUtil.objectNotEmpty(Commond.getJointIdNew())) {
				validCommond.setJointId(Commond.getJointIdNew());
			}
			String deptCode = dep.getDeptCode();
			String applyNum = trainingPlanService.getMaxApplyNum(deptCode,Integer.valueOf(Commond.getStartPlanDateNewStr().substring(0,4)));
			applyNum = "P" + applyNum.substring(1, 5) + deptCode + StringUtil.CompleteNum(Integer.valueOf(applyNum.substring(8)) + 1, 2);
			validCommond.setApplyNum(applyNum);
			validCommond.setIssuedState(TrainingPlan.ISSUEDSTATE_W);
			validCommond.setPublishState(TrainingPlan.PUBLISHSTATE_W);
			validCommond.setAuditState(TrainingPlan.AUDITSTATE_W);
			validCommond.setOperationDate(new Date());
			trainingPlanService.save(validCommond);
			resultState.setMessage("新增成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		} catch (Exception e) {
			System.out.println("新增培训计划失败！");
			resultState.setMessage("新增失败，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 部委更新培训计划
	 * 
	 * @author RongSL
	 * */
	@RequestMapping("/updateTrainingPlan")
	public void updateTrainingPlan(@ModelAttribute("result") TrainingPlanBean Commond, @ModelAttribute("resultState") ResultState resultState) {
		try {
			if (PropertyUtil.objectNotEmpty(Commond.getPlanId())) {
				TrainingPlanValidCommond vCommond = new TrainingPlanValidCommond();
				vCommond.setPlanId(Commond.getPlanId());
				vCommond = trainingPlanService.findTrainingPlan(vCommond);
				vCommond.setOperationDate(new Date());
				if (PropertyUtil.objectNotEmpty(Commond.getClassNameNew())) {
					vCommond.setClassName(Commond.getClassNameNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getClassObjectiveNew())) {
					vCommond.setClassObjective(Commond.getClassObjectiveNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getClassValuesNew())) {
					vCommond.setClassValues(Commond.getClassValuesNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getLinkManNew())) {
					vCommond.setLinkMan(Commond.getLinkManNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getLinkModeNew())) {
					vCommond.setLinkMode(Commond.getLinkModeNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getFaxNew())) {
					vCommond.setFax(Commond.getFaxNew());
				}
				// if (PropertyUtil.objectNotEmpty(Commond.getPlanDateNew())) {
				// vCommond.setPlanDate(Commond.getPlanDateNew());
				// }
				if (PropertyUtil.objectNotEmpty(Commond.getStartPlanDateNewStr())) {
					vCommond.setStartPlanDateStr(Commond.getStartPlanDateNewStr());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getEndPlanDateNewStr())) {
					vCommond.setEndPlanDateStr(Commond.getEndPlanDateNewStr());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getPlanDayNew())) {
					vCommond.setPlanDay(Commond.getPlanDayNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getTrainingAddressNew())) {
					vCommond.setTrainingAddress(Commond.getTrainingAddressNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getTrainingObjectNew())) {
					vCommond.setTrainingObject(Commond.getTrainingObjectNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getJointNameNew())) {
					vCommond.setJointName(Commond.getJointNameNew());
				}
				if (PropertyUtil.objectNotEmpty(Commond.getJointIdNew())) {
					vCommond.setJointId(Commond.getJointIdNew());
				}

				// 更新计划名额
				Integer planNum = 0;
				ClassPlanApplyValidCommond co = null;
				com.eorchis.module.trainingplan.domain.ClassPlanApplyQueryBean coo = null;
				List<ClassPlanApplyQueryBean> cpav = new ArrayList<ClassPlanApplyQueryBean>();
				if (PropertyUtil.objectNotEmpty(Commond.getDeptNames())) {
					for (int i = 0; i < Commond.getDeptNames().length; i++) {
						if (Commond.getDeptIds()[i].equals("1"))
							continue;
						// 查询是否已经初始化过计划报名
						ClassPlanApplyQueryCommond q = new ClassPlanApplyQueryCommond();
						q.setSearchClassId(vCommond.getApplyNum());
						q.setSearchDeptCode(Commond.getDeptNames()[i]);
						List<?> r = classPlanApplyService.findList(q);
						if (PropertyUtil.objectNotEmpty(r)) {
							// 当没有版本时直接保存数据
							if (!PropertyUtil.objectNotEmpty(vCommond.getVersion())) {
								// update
								co = (ClassPlanApplyValidCommond) r.get(0);
								co.setCityPlanCount(StringUtil.nullToNumber(Commond.getCityPlanCounts()[i]));
								co.setCountyPlanCount(StringUtil.nullToNumber(Commond.getCountyPlanCounts()[i]));
								co.setPlanCount(StringUtil.nullToNumber(Commond.getCityPlanCounts()[i]) + StringUtil.nullToNumber(Commond.getCountyPlanCounts()[i]));
								classPlanApplyService.update(co);
								coo = new ClassPlanApplyQueryBean();
								BeanUtils.copyProperties(co, coo);
								cpav.add(coo);
							} else {
								co = (ClassPlanApplyValidCommond) r.get(0);
								coo = new ClassPlanApplyQueryBean();
								BeanUtils.copyProperties(co, coo);
								coo.setCityPlanCount(StringUtil.nullToNumber(Commond.getCityPlanCounts()[i]));
								coo.setCountyPlanCount(StringUtil.nullToNumber(Commond.getCountyPlanCounts()[i]));
								coo.setPlanCount(StringUtil.nullToNumber(Commond.getCityPlanCounts()[i]) + StringUtil.nullToNumber(Commond.getCountyPlanCounts()[i]));
								// 更新的时候不在保存在数据库
								cpav.add(coo);
							}
						}
						// else {
						// co.setCityPlanCount(Commond.getCityPlanCounts()[i]);
						// co.setCountyPlanCount(Commond.getCountyPlanCounts()[i]);
						// co.setPlanCount(Commond.getCityPlanCounts()[i] +
						// Commond.getCountyPlanCounts()[i]);
						// co.setDeptId(Commond.getDeptIds()[i]);
						// co.setDeptName(Commond.getDeptNames()[i]);
						// co.setDeptCode(Commond.getDeptNames()[i]);
						// co.setClassId(vCommond.getApplyNum());
						// classPlanApplyService.save(co);
						// }
						planNum += StringUtil.nullToNumber(coo.getPlanCount());
					}
					vCommond.setPlanNum(planNum);
				}

				// 给计划集合排序
//				sort(cpav);

				if (PropertyUtil.objectNotEmpty(vCommond.getVersion())) {
					TrainingPlanFileValidCommond tpf = new TrainingPlanFileValidCommond();
					tpf.setApplyNum(vCommond.getApplyNum());
					tpf = trainingPlanService.findTrainingPlan(tpf);
					BeanUtils.copyProperties(vCommond, tpf, new String[] { "planId", "applyNum", "createDate" });
					trainingPlanService.update(tpf);

					// ClassPlanApplyQueryCommond query = new
					// ClassPlanApplyQueryCommond();
					// query.setSearchClassId(tpf.getApplyNum());
					// List<ClassPlanApplyQueryBean>
					// list=trainingPlanService.findClassPlanApplyQueryBeanList(query);
					String array = JSON.toJSONString(cpav);
					trainingPlanService.updatePlanFile(tpf, array);
				} else {
					trainingPlanService.update(vCommond);
				}
				resultState.setMessage("更新成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			} else {
				System.out.println("缺少参数！");
				resultState.setMessage("缺少参数！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		} catch (Exception e) {
			System.out.println("更新培训计划出错！");
			resultState.setMessage("更新培训计划出错！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 查看培训计划
	 * 
	 * @author RongSL
	 * */
	@RequestMapping("/findTrainingPlan")
	public void findTrainingPlan(@ModelAttribute("result") TrainingPlanBean bean, @ModelAttribute("resultState") ResultState resultState, HttpServletRequest request) {
		try {
			TrainingPlanValidCommond tpv = null;// 主对比列表
			TrainingPlanFileValidCommond tpf = null;// 辅对比数据
			if (PropertyUtil.objectNotEmpty(bean.getPlanId())) {
				tpv = new TrainingPlanValidCommond();
				tpv.setPlanId(bean.getPlanId());
				tpv = trainingPlanService.findTrainingPlan(tpv);
				String opinion = null;
				if (PropertyUtil.objectNotEmpty(tpv.getVersion())) {
					Role role = (Role) request.getSession().getAttribute("currentRole");
					if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_BW_ADMIN)) {
						tpf = new TrainingPlanFileValidCommond();
						tpf.setApplyNum(tpv.getApplyNum());
						// tpf.setVersion(tpv.getVersion());
						tpf = trainingPlanService.findTrainingPlan(tpf);
						if (PropertyUtil.objectNotEmpty(tpf)) {
							TrainingPlanFileValidCommond tpf2 = new TrainingPlanFileValidCommond();
							// 如果操作时间大于培训计划，则新版本为归档，旧版本为培训计划
							if (tpv.getOperationDate().after(tpf.getOperationDate()) || tpv.getOperationDate().toString().equals(tpf.getOperationDate().toString())) {
								// BeanUtils.copyProperties(tpf, tpf);
							} else {
								BeanUtils.copyProperties(tpf, tpf2);
								BeanUtils.copyProperties(tpv, tpf);
								tpf2.setPlanId(tpv.getPlanId());
								BeanUtils.copyProperties(tpf2, tpv);
							}
						}
					} else if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_ZZB_ADMIN)) {
						TrainingPlanFileZZBValidCommond tpf2 = new TrainingPlanFileZZBValidCommond();
						tpf2.setApplyNum(tpv.getApplyNum());
						// tpf2.setVersion(tpv.getVersion());
						tpf2 = trainingPlanService.findTrainingPlan(tpf2);
						if (PropertyUtil.objectNotEmpty(tpf2)) {
							tpf = new TrainingPlanFileValidCommond();
							// 如果操作时间大于培训计划，则新版本为归档，旧版本为培训计划
							if (tpv.getOperationDate().after(tpf2.getOperationDate()) || tpv.getOperationDate().toString().equals(tpf2.getOperationDate().toString())) {
								BeanUtils.copyProperties(tpf2, tpf);
							} else {
								BeanUtils.copyProperties(tpv, tpf);
								tpf2.setPlanId(tpv.getPlanId());
								BeanUtils.copyProperties(tpf2, tpv);
							}
						}
					} else if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_DW_ADMIN)) {
						Department d = (Department) request.getSession().getAttribute("currentScope");
						tpv.setDeptId(d.getDeptID());
						opinion = trainingPlanService.getOpinion(tpv);
					}
				}
				TrainingPlanBean b = trainingPlanService.ValidCommondToTrainingPlanBean(tpv, tpf);
				b.setOpinion(PropertyUtil.objectNotEmpty(opinion) && !opinion.equals("null") ? opinion : "");
				BeanUtils.copyProperties(b, bean);
				resultState.setMessage("查询成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			} else {
				resultState.setMessage("查询失败，缺少培训计划ID！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		} catch (Exception e) {
			System.out.println("查看培训计划出错！");
			e.printStackTrace();
			resultState.setMessage("查询失败，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 查看计划名额
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@SuppressWarnings("unchecked")
	@RequestMapping("/lookPlanPlaces")
	public void lookPlanPlaces(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState, HttpServletRequest request) {
		try {
			if (PropertyUtil.objectNotEmpty(queryCommond.getSearchPlanId()) && PropertyUtil.objectNotEmpty(queryCommond.getSearchApplyPlan())) {
				List<ClassPlanApplyQueryBean> resultList1 = null;// 对比集合
				List<ClassPlanApplyQueryBean> resultList2 = null;// 被对比集合
				Role role = (Role) request.getSession().getAttribute("currentRole");
				List<TrainingPlanApplyContrast> l = null;
				TrainingPlanValidCommond tpv = new TrainingPlanValidCommond();
				tpv.setPlanId(queryCommond.getSearchPlanId());
				// 查询培训计划
				tpv = trainingPlanService.findTrainingPlan(tpv);
				ClassPlanApplyQueryCommond query = new ClassPlanApplyQueryCommond();
				query.setSearchClassId(tpv.getApplyNum());
				// 判断当前有没有版本号
				if (PropertyUtil.objectNotEmpty(tpv.getVersion())) {
					// 查询培训计划归档
					if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_BW_ADMIN)) {
						TrainingPlanFileValidCommond tpf = new TrainingPlanFileValidCommond();
						tpf.setApplyNum(tpv.getApplyNum());
						// tpf.setVersion(tpv.getVersion());
						tpf = trainingPlanService.findTrainingPlan(tpf);
						if (PropertyUtil.objectNotEmpty(tpf)) {
							if (queryCommond.getSearchApplyPlan().equals(TrainingPlan.publicStatus_Y)) {// 查看新版计划名额
								if (tpv.getOperationDate().after(tpf.getOperationDate()) || tpv.getOperationDate().toString().equals(tpf.getOperationDate().toString())) {
									resultList1 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
									resultList2 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())), ClassPlanApplyQueryBean.class);
								} else {
									resultList1 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())), ClassPlanApplyQueryBean.class);
									resultList2 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
								}
							} else {// 查看旧版计划名额
								if (tpv.getOperationDate().after(tpf.getOperationDate()) || tpv.getOperationDate().toString().equals(tpf.getOperationDate().toString())) {
									resultList1 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())), ClassPlanApplyQueryBean.class);
									resultList2 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
								} else {
									resultList1 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
									resultList2 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())), ClassPlanApplyQueryBean.class);
								}
							}
						}
					} else if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_ZZB_ADMIN)) {
						TrainingPlanFileZZBValidCommond tpf = new TrainingPlanFileZZBValidCommond();
						tpf.setApplyNum(tpv.getApplyNum());
						// tpf.setVersion(tpv.getVersion());
						tpf = trainingPlanService.findTrainingPlan(tpf);
						if (PropertyUtil.objectNotEmpty(tpf)) {
							if (PropertyUtil.objectNotEmpty(tpf.getPlanApply())) {
								if (queryCommond.getSearchApplyPlan().equals(TrainingPlan.publicStatus_Y)) {// 查看新版计划名额
									if (tpf.getOperationDate().after(tpv.getOperationDate())) {
										resultList1 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())), ClassPlanApplyQueryBean.class);
										resultList2 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
									} else {
										resultList1 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
										resultList2 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())), ClassPlanApplyQueryBean.class);
									}
								} else {// 查看旧版计划名额
									if (tpf.getOperationDate().after(tpv.getOperationDate())) {
										resultList1 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
										resultList2 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())), ClassPlanApplyQueryBean.class);
									} else {
										resultList1 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())), ClassPlanApplyQueryBean.class);
										resultList2 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
									}
								}
							} else {
								// 没有归档
								resultList1 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
							}
						} else {
							// 没有归档
							resultList1 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
						}
					} else {
						// 地方管理员查看
						Department dep = (Department) request.getSession().getAttribute("currentScope");
						query.setSearchDeptId(dep.getDeptID());
						resultList1 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
					}
				} else {
					// 没有提交过审核
					resultList1 = trainingPlanService.findClassPlanApplyQueryBeanList(query);
				}
				
				/**
				 * 将“企业”从集合中删去		垃圾代码
				 * @author RongSL
				 * @Date 2016-11-16
				 * */
				if(PropertyUtil.objectNotEmpty(resultList1)){
					for(int c=0;c<resultList1.size();c++){
						if(resultList1.get(c).getDeptId().equals(DeptConstants.PROVINCE_DEPNAME_DEPID_MAPPING.get("企业"))){
							resultList1.remove(c);
						}
					}
				}
				if(PropertyUtil.objectNotEmpty(resultList2)){
					for(int c=0;c<resultList2.size();c++){
						if(resultList2.get(c).getDeptId().equals(DeptConstants.PROVINCE_DEPNAME_DEPID_MAPPING.get("企业"))){
							resultList2.remove(c);
						}
					}
				}
				
				l = trainingPlanService.classPlanApplyQueryBeanToTrainingPlanApplyContrast(resultList1, resultList2);
				
				queryCommond.setResultList(l);
				resultState.setMessage("查询成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			} else {
				resultState.setMessage("缺少参数，请重试！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 批量删除培训计划
	 * 
	 * @author RongSL
	 * */
	@RequestMapping("/batchDeleteTrainingPlan")
	public void batchDeleteTrainingPlan(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		try {
			// 判断计划是否可以删除
			if (trainingPlanService.judgePlanDelete(queryCommond)) {
				List<String> list = new ArrayList<String>();
				TrainingPlanValidCommond tp = new TrainingPlanValidCommond();
				for (String id : queryCommond.getSearchPlanIds()) {
					tp.setPlanId(id);
					tp = trainingPlanService.find(id);
					list.add(tp.getApplyNum());
					trainingPlanService.delete(tp);
				}
				String applyNums[] = list.toArray(new String[] {});
				queryCommond.setApplyNums(applyNums);
				// 如果曾经导入过名额，则清空相关数据
				trainingPlanService.deletePlanOther(queryCommond);

				resultState.setMessage("删除成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			} else {
				resultState.setMessage("只有未审核的培训计划才可以删除！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		} catch (Exception e) {
			System.out.println("删除培训计划失败！");
			resultState.setMessage("删除培训计划失败，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 提交审核
	 * 
	 * @author RongSL
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@SuppressWarnings("unchecked")
	@RequestMapping("/submitAudit")
	public void submitAudit(TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		ClassPlanApplyQueryCommond query = null;
		Date d = new Date();
		try {
			if (PropertyUtil.objectNotEmpty(queryCommond.getSearchPlanIds())) {
				for (String id : queryCommond.getSearchPlanIds()) {
					TrainingPlanValidCommond vCommond = new TrainingPlanValidCommond();
					vCommond.setPlanId(id);
					vCommond = trainingPlanService.findTrainingPlan(vCommond);
					String array = null;
					// 查询当前的计划名额，准备入档
					query = new ClassPlanApplyQueryCommond();
					query.setSearchClassId(vCommond.getApplyNum());
					List<ClassPlanApplyQueryBean> resultList = trainingPlanService.findClassPlanApplyQueryBeanList(query);
					// 导入名额以后才能提交审核，判断是否已经导入名额
					if (PropertyUtil.objectNotEmpty(resultList)) {
						// 计划名额入档
						// TrainingPlanFileValidCommond tpf = new
						// TrainingPlanFileValidCommond();
						TrainingPlanFileValidCommond tpf = new TrainingPlanFileValidCommond();
						// tpf.setApplyNum(vCommond.getApplyNum());
						// tpf.setVersion(vCommond.getVersion());

						// 判断是否已有归档
						if (PropertyUtil.objectNotEmpty(vCommond.getVersion())) {
							// 查询版本号最大的一版计划
							tpf.setApplyNum(vCommond.getApplyNum());
							tpf = trainingPlanService.findTrainingPlan(tpf);
							if (vCommond.getOperationDate().after(tpf.getOperationDate())||vCommond.getOperationDate().equals(tpf.getOperationDate())) {
								BeanUtils.copyProperties(vCommond, tpf);
								tpf.setVersion(tpf.getVersion() + 1);
								array = JSON.toJSONString(resultList);// Json转String
								trainingPlanService.save(tpf);
							} else {
								BeanUtils.copyProperties(tpf, vCommond, new String[] { "planId", "createDate" });
								List<ClassPlanApplyQueryBean> resultList2 = JsonToT.getPersons(new String(tpf.getPlanApply().getBytes((long) 1, (int) tpf.getPlanApply().length())),ClassPlanApplyQueryBean.class);
								// 将归档入计划
								ClassPlanApplyValidCommond co = null;
								for (ClassPlanApplyQueryBean r : resultList2) {
									// 查询是否已经初始化过计划报名
									ClassPlanApplyQueryCommond q = new ClassPlanApplyQueryCommond();
									q.setSearchClassId(vCommond.getApplyNum());
									q.setSearchDeptCode(r.getDeptCode());
									List<?> li = classPlanApplyService.findList(q);
									co = (ClassPlanApplyValidCommond) li.get(0);
									BeanUtils.copyProperties(r, co);
									// 更新计划名额
									classPlanApplyService.update(co);
								}
								array = JSON.toJSONString(resultList2);// Json转String
							}
						} else {
							vCommond.setVersion(1.0);// 更新计划版本号
							BeanUtils.copyProperties(vCommond, tpf);
							tpf.setVersion(vCommond.getVersion());
							tpf.setOperationDate(d);
							array = JSON.toJSONString(resultList);// Json转String
							trainingPlanService.save(tpf);
						}

						// 更新状态
						vCommond.setVersion(vCommond.getVersion() + 1);
						vCommond.setAuditState(TrainingPlan.AUDITSTATE_D);
						vCommond.setOperationDate(d);
						trainingPlanService.update(vCommond);

						trainingPlanService.updatePlanFile(tpf, array);
						resultState.setMessage("审核成功！");
						resultState.setState(ResultState.RESULT_STATE_SUCCESS);

						try {
							/**
							 * 添加提醒
							 * 
							 * @Date 2016-05-12
							 * @author RongSL
							 * @Params 提醒类型，承办部委名称，培训班名称，提醒分类
							 * */
							remindService.remindOperate(Remind.TJPXJH, vCommond.getUndertakeName(), vCommond.getClassName(), vCommond.getPlanId(), Remind.PXJH);
						} catch (Exception e) {
							System.out.println("新增培训班提醒接口出错了！");
						}

					} else {
						resultState.setMessage("导入名额后才可以提交审核！");
						resultState.setState(ResultState.RESULT_STATE_FAIL);
					}
				}
			} else {
				resultState.setMessage("缺少培训计划ID！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("培训计划提交审核出错！");
			resultState.setMessage("培训计划提交审核出错！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 撤回审核
	 * 
	 * @author RongSL
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/recallAudit")
	public void recallAudit(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		try {
			// 判断此计划是否可以撤回。
			// if (trainingPlanService.judgePlanWithdraw(queryCommond)) {
			TrainingPlanValidCommond tp = new TrainingPlanValidCommond();
			for (String id : queryCommond.getSearchPlanIds()) {
				tp.setPlanId(id);
				tp = trainingPlanService.findTrainingPlan(tp);
				tp.setAuditState(TrainingPlan.AUDITSTATE_W);
				trainingPlanService.update(tp);
			}
			resultState.setMessage("撤回审核成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			// } else {
			// resultState.setMessage("只允许撤回未下发或待审核的培训计划！");
			// resultState.setState(ResultState.RESULT_STATE_FAIL);
			// }
		} catch (Exception e) {
			System.out.println("培训计划撤回审核失败！");
			resultState.setMessage("培训计划撤回审核失败，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 审核操作和保存
	 * 
	 * @author RongSL
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/adoptAudit")
	public void adoptAudit(TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		// ClassPlanApplyQueryCommond query = null;
		// List<ClassPlanApplyQueryBean> resultList = null;
		int planNum = 0;// 计划总人数
		Date d = new Date();
		try {
			if (PropertyUtil.objectNotEmpty(queryCommond.getSearchPlanId())) {
				TrainingPlanValidCommond vCommond = new TrainingPlanValidCommond();
				vCommond.setPlanId(queryCommond.getSearchPlanId());
				vCommond = trainingPlanService.findTrainingPlan(vCommond);
				vCommond.setOperationDate(d);
				// 更新计划名额
				ClassPlanApplyValidCommond co = null;
				ClassPlanApplyQueryBean coo = null;
				List<ClassPlanApplyQueryBean> cpa = new ArrayList<ClassPlanApplyQueryBean>();
				for (int i = 0; i < queryCommond.getDeptNames().length; i++) {
					if (queryCommond.getDeptIds()[i].equals("1"))
						continue;
					// 查询是否已经初始化过计划报名
					ClassPlanApplyQueryCommond q = new ClassPlanApplyQueryCommond();
					q.setSearchClassId(vCommond.getApplyNum());
					q.setSearchDeptCode(queryCommond.getDeptNames()[i]);
					List<?> r = classPlanApplyService.findList(q);
					coo = new ClassPlanApplyQueryBean();
					if (!queryCommond.getSearchAuditState().equals(TrainingPlan.AUDITSTATE_D)) {
						// update
						co = (ClassPlanApplyValidCommond) r.get(0);
						co.setCityPlanCount(queryCommond.getCityPlanCounts()[i]);
						co.setCountyPlanCount(queryCommond.getCountyPlanCounts()[i]);
						co.setPlanCount(queryCommond.getCityPlanCounts()[i] + queryCommond.getCountyPlanCounts()[i]);
						classPlanApplyService.update(co);
						BeanUtils.copyProperties(co, coo);
						cpa.add(coo);
					} else {
						if (PropertyUtil.objectNotEmpty(r)) {
							co = (ClassPlanApplyValidCommond) r.get(0);
							BeanUtils.copyProperties(co, coo);
							coo.setCityPlanCount(queryCommond.getCityPlanCounts()[i]);
							coo.setCountyPlanCount(queryCommond.getCountyPlanCounts()[i]);
							coo.setPlanCount(StringUtil.nullToNumber(queryCommond.getCityPlanCounts()[i]) + StringUtil.nullToNumber(queryCommond.getCountyPlanCounts()[i]));
							cpa.add(coo);
							// classPlanApplyService.update(co);
						}
					}
					/*
					 * else {
					 * co.setCityPlanCount(queryCommond.getCityPlanCounts()[i]);
					 * co
					 * .setCountyPlanCount(queryCommond.getCountyPlanCounts()[i
					 * ]); co.setPlanCount(queryCommond.getCityPlanCounts()[i] +
					 * queryCommond.getCountyPlanCounts()[i]);
					 * co.setDeptId(queryCommond.getDeptIds()[i]);
					 * co.setDeptName(queryCommond.getDeptNames()[i]);
					 * co.setDeptCode(queryCommond.getDeptNames()[i]);
					 * co.setClassId(vCommond.getApplyNum());
					 * classPlanApplyService.save(co); }
					 */
					planNum += coo.getPlanCount();
				}

				// 排序
//				sort(cpa);

				// 如果是保存操作则不更改当前状态
				if (!queryCommond.getSearchAuditState().equals(TrainingPlan.AUDITSTATE_D)) {
					vCommond.setAuditState(queryCommond.getSearchAuditState());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getRejectReason())) {
					vCommond.setRejectReason(queryCommond.getRejectReason());
				}

				vCommond.setPlanNum(planNum);// 更新计划总人数

				if (PropertyUtil.objectNotEmpty(queryCommond.getClassName())) {
					vCommond.setClassName(queryCommond.getClassName());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getClassObjective())) {
					vCommond.setClassObjective(queryCommond.getClassObjective());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getClassValues())) {
					vCommond.setClassValues(queryCommond.getClassValues());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getLinkMan())) {
					vCommond.setLinkMan(queryCommond.getLinkMan());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getJointName())) {
					vCommond.setJointName(queryCommond.getJointName());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getJointId())) {
					vCommond.setJointId(queryCommond.getJointId());
				}
				// if(PropertyUtil.objectNotEmpty(queryCommond.getUndertakeName())){
				// vCommond.setUndertakeName(queryCommond.getUndertakeName());
				// }
				// if(PropertyUtil.objectNotEmpty(queryCommond.getUndertakeId())){
				// vCommond.setUndertakeId(queryCommond.getUndertakeId());
				// }
				if (PropertyUtil.objectNotEmpty(queryCommond.getLinkMode())) {
					vCommond.setLinkMode(queryCommond.getLinkMode());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getFax())) {
					vCommond.setFax(queryCommond.getFax());
				}
				// if (PropertyUtil.objectNotEmpty(queryCommond.getPlanDate()))
				// {
				// vCommond.setPlanDate(queryCommond.getPlanDate());
				// }
				if (PropertyUtil.objectNotEmpty(queryCommond.getPlanDay())) {
					vCommond.setPlanDay(queryCommond.getPlanDay());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getTrainingAddress())) {
					vCommond.setTrainingAddress(queryCommond.getTrainingAddress());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getTrainingObject())) {
					vCommond.setTrainingObject(queryCommond.getTrainingObject());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getStartPlanDateNewStr())) {
					vCommond.setStartPlanDateStr(queryCommond.getStartPlanDateNewStr());
				}
				if (PropertyUtil.objectNotEmpty(queryCommond.getEndPlanDateNewStr())) {
					vCommond.setEndPlanDateStr(queryCommond.getEndPlanDateNewStr());
				}

				if (PropertyUtil.objectNotEmpty(queryCommond.getSearchAuditState())) {

					TrainingPlanFileZZBValidCommond tpf = new TrainingPlanFileZZBValidCommond();
					// 查询版本号最大的一版计划
					tpf.setApplyNum(vCommond.getApplyNum());
					tpf = trainingPlanService.findTrainingPlan(tpf);

					if (!PropertyUtil.objectNotEmpty(tpf)) {
						tpf = new TrainingPlanFileZZBValidCommond();
						BeanUtils.copyProperties(vCommond, tpf);
						tpf.setCreateDate(d);
						trainingPlanService.save(tpf);
						// 更新归档中的计划名额
						String array = JSON.toJSONString(cpa);// Json转String
						// trainingPlanService.updatePlanFile(tpf, array);
						trainingPlanService.updatePlanFile(tpf, array);

						// tpf=trainingPlanService.findTrainingPlan(tpf);
					}
					// 中组部的审核通过要发布新版
					if (queryCommond.getSearchAuditState().equals(TrainingPlan.AUDITSTATE_D)) {
						// 中组部保存操作，查询当前的计划名额，准备入档
						// query = new ClassPlanApplyQueryCommond();
						// query.setSearchClassId(vCommond.getApplyNum());
						// List<ClassPlanApplyQueryBean> resultList =
						// trainingPlanService.findClassPlanApplyQueryBeanList(query);
						// 计划名额入档
						// tpf.setApplyNum(vCommond.getApplyNum());
						// tpf.setVersion(vCommond.getVersion());

						// 判断是否已有归档
						if (PropertyUtil.objectNotEmpty(vCommond.getVersion())) {

							// 判断是否已有归档
							BeanUtils.copyProperties(vCommond, tpf, new String[] { "planId", "applyNum", "createDate" });

							// if(vCommond.getVersion()+1==tpf.getVersion()){
							// System.out.println("hello world!");
							// }else{
							trainingPlanService.update(tpf);
							// }
						}
						// trainingPlanService.updateTrainingPlanValid(vCommond);

						// 更新归档中的计划名额
						String array = JSON.toJSONString(cpa);// Json转String
						trainingPlanService.updatePlanFile(tpf, array);
						// } else {
					} else {
						// 审核通过和审核驳回操作，查询当前的计划名额，准备入档
						String array = null;
						if (vCommond.getOperationDate().after(tpf.getOperationDate())) {
							// query = new ClassPlanApplyQueryCommond();
							// query.setSearchClassId(vCommond.getApplyNum());
							// List<ClassPlanApplyQueryBean> resultList =
							// trainingPlanService.findClassPlanApplyQueryBeanList(query);

							vCommond.setVersion(vCommond.getVersion() + 1);
							BeanUtils.copyProperties(vCommond, tpf, new String[] { "createDate" });
							trainingPlanService.save(tpf);
							// 更新归档中的计划名额
							array = JSON.toJSONString(cpa);// Json转String
						} else {
							BeanUtils.copyProperties(tpf, vCommond, new String[] { "planId", "applyNum", "createDate" });
							// 更新归档中的计划名额
							array = JSON.toJSONString(cpa);// Json转String
							// array = JSON.toJSONString(tpf.getPlanApply());//
							// Json转String
						}

						// 更新归档中的计划名额
						trainingPlanService.updatePlanFile(tpf, array);

						// 更新当前版本
						vCommond.setOperationDate(d);
						trainingPlanService.update(vCommond);
					}
				}

				resultState.setMessage("审核成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);

				String c = null;
				if (queryCommond.getSearchAuditState().equals(TrainingPlan.AUDITSTATE_B)) {
					c = "建议修改";
				} else if (queryCommond.getSearchAuditState().equals(TrainingPlan.AUDITSTATE_T)) {
					c = "初审通过";
				} else if (queryCommond.getSearchAuditState().equals(TrainingPlan.AUDITSTATE_F)) {
					c = "否决";
				}
				if (!queryCommond.getSearchAuditState().equals(TrainingPlan.AUDITSTATE_D)) {
					try {
						/**
						 * 添加提醒
						 * 
						 * @Date 2016-05-12
						 * @author RongSL
						 * @Params 提醒类型，承办部委名称，培训班名称，提醒分类
						 * */
						remindService.remindOperate(Remind.SHPXJH, vCommond.getClassName(), c, vCommond.getUndertakeName(), vCommond.getPlanId(), Remind.PXJH);
					} catch (Exception e) {
						System.out.println("审核计划提醒接口出错了！");
					}
				}
			} else {
				resultState.setMessage("缺少培训计划ID！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		} catch (Exception e) {
			System.out.println("培训计划审核操作出错！");
			e.printStackTrace();
			resultState.setMessage("培训计划审核操作出错，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 导入培训班详情
	 * 
	 * @authOr RongSL
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@SuppressWarnings({ "unchecked", "unused" })
	// @RequestMapping(value = "/ImportDetailsPlacesForExcel")
	@RequestMapping(value = "/ImportDetailsPlacesForExcel", method = RequestMethod.POST)
	@ResponseBody
	public void ImportDetailsPlacesForExcel(TrainingPlanValidCommond valid, HttpServletRequest request, HttpServletResponse response, @ModelAttribute("ResultSate") ResultState resultState, Model model) {

		ResultJson resultJson = new ResultJson();
		resultJson.setMsg("导入成功！");
		resultJson.setSuccess(true);
		StringBuffer msg = new StringBuffer();
		HSSFWorkbook hssfWorkbook = null;
		HSSFSheet sheet = null;
		TrainingPlanValidCommond tpv = null;
		DecimalFormat df = new DecimalFormat("0");
		String applyNum;// 计划编号
		Integer planCount = 0;// 计划总数
		Row o = null;
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			for (MultipartFile multipartFile : fileMap.values()) {
				CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
				FileItem item = commonsMultipartFile.getFileItem();
				InputStream is = null;
				is = item.getInputStream();
				hssfWorkbook = new HSSFWorkbook(is);
				is.close();
				sheet = hssfWorkbook.getSheetAt(0);
				if (sheet.getPhysicalNumberOfRows() != 14) {
					resultJson.setMsg("未使用指定模块，请重新导出！" + "\n");
					resultJson.setSuccess(false);
				} else {
					tpv = new TrainingPlanValidCommond();
					applyNum = sheet.getRow(2).getCell(1).toString();
					if (!PropertyUtil.objectNotEmpty(applyNum)) {
						msg.append("计划编号不能为空！" + "\n");
						resultJson.setSuccess(false);
						return;
					}
					if (!valid.getApplyNum().equals(applyNum)) {
						msg.append("所选培训计划与导入的培训计划不同，请选择正确的培训计划！" + "\n");
						resultJson.setSuccess(false);
						return;
					}
					String name = sheet.getRow(0).getCell(0).toString();
					tpv.setApplyNum(applyNum);
					tpv.setOperationDate(new Date());
					TrainingPlanQueryCommond tpq = new TrainingPlanQueryCommond();
					tpq.setSearchApplyNum(applyNum);
					Role role = (Role) request.getSession().getAttribute("currentRole");
					if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_BW_ADMIN)) {
						Department dept = (Department) request.getSession().getAttribute("currentScope");
						tpq.setSearchUndertakeID(dept.getDeptID());
					}
					List<TrainingPlanValidCommond> list = (List<TrainingPlanValidCommond>) trainingPlanService.findList(tpq);
					if (PropertyUtil.objectNotEmpty(list)) {
						tpv = list.get(0);
						if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_ZZB_ADMIN)) {
							if (tpv.getAuditState().equals(TrainingPlan.AUDITSTATE_W)) {
								msg.append("此计划不存在！" + "\n");
								resultJson.setSuccess(false);
								return;
							}
						}
						if (tpv.getPublishState().equals(TrainingPlan.PUBLISHSTATE_Y)) {
							msg.append("不允许更改已经发布的培训计划！" + "\n");
							resultJson.setSuccess(false);
							return;
						}
						for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
							o = sheet.getRow(i);
							switch (i) {
							case 1:
								String className = o.getCell(1).toString();
								if(PropertyUtil.objectNotEmpty(className)){
									try{
										className = o.getCell(1).getStringCellValue();
									}catch(Exception e){
										className = o.getCell(1).toString().split("\\.")[0];
									}
									tpv.setClassName(className);
								}else{
									msg.append("计划名称不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 2:
								applyNum = o.getCell(1).toString();
								tpv.setApplyNum(applyNum);
								break;
							case 3:
								String undertakeName = o.getCell(1).toString();
								tpv.setUndertakeName(undertakeName);
								tpq.setDeptName(undertakeName);
								String deptId = trainingPlanService.findAdminDeptId(tpq);
								if (!PropertyUtil.objectNotEmpty(deptId)) {
									msg.append(undertakeName + "-部门不存在！" + "\n");
									resultJson.setSuccess(false);
								}
								tpv.setUndertakeId(deptId);
								break;
							case 4:
								String jointName = o.getCell(1).toString();
								if (PropertyUtil.objectNotEmpty(jointName)) {
									tpv.setJointName(jointName);
									tpq.setDeptName(jointName);
									deptId = trainingPlanService.findAdminDeptId(tpq);
									if (!PropertyUtil.objectNotEmpty(deptId)) {
										msg.append(jointName + "-部门不存在！" + "\n");
										resultJson.setSuccess(false);
									}
									tpv.setJointId(deptId);
								}
								break;
							case 5:
								int type;
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									type = o.getCell(1).getCellType();
									if (type == 1) {
										tpv.setStartPlanDateStr(o.getCell(1).getStringCellValue());
									} else {
										tpv.setStartPlanDate(o.getCell(1).getDateCellValue());
									}
								}else{
									msg.append("计划开始时间不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 6:
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									type = o.getCell(1).getCellType();
									if (type == 1) {
										tpv.setEndPlanDateStr(o.getCell(1).getStringCellValue());
									} else {
										tpv.setEndPlanDate(o.getCell(1).getDateCellValue());
									}
									
									//设置学制
									Long t = tpv.getEndPlanDate().getTime() - tpv.getStartPlanDate().getTime();
									t = t / 86400000;
									tpv.setPlanDay(t.intValue()+1);
								}else{
									msg.append("计划结束时间不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 7:
								String classObjective;
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									try{
										classObjective = o.getCell(1).getStringCellValue();
									}catch(Exception e){
										classObjective = o.getCell(1).toString().split("\\.")[0];
									}
									tpv.setClassObjective(classObjective);
								}else{
									msg.append("办班目的不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 8:
								String classValues;
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									try{
										classValues = o.getCell(1).getStringCellValue();
									}catch(Exception e){
										classValues = o.getCell(1).toString().split("\\.")[0];
									}
									tpv.setClassValues(classValues);
								}else{
									msg.append("培训内容不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 9:
								String trainingObject;
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									try{
										trainingObject = o.getCell(1).getStringCellValue();
									}catch(Exception e){
										trainingObject = o.getCell(1).toString().split("\\.")[0];
									}
									tpv.setTrainingObject(trainingObject);
								}else{
									msg.append("调训对象不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 10:
								String trainingAddress;
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									try{
										trainingAddress = o.getCell(1).getStringCellValue();
									}catch(Exception e){
										trainingAddress = o.getCell(1).toString().split("\\.")[0];
									}
									tpv.setTrainingAddress(trainingAddress);
								}else{
									msg.append("培训地点不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 11:
								String linkMan;
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									try{
										linkMan = o.getCell(1).getStringCellValue();
									}catch(Exception e){
										linkMan = o.getCell(1).toString().split("\\.")[0];
									}
									tpv.setLinkMan(linkMan);
								}else{
									msg.append("联系人不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 12:
								String linkMode;
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									try {
										linkMode = df.format(o.getCell(1).getNumericCellValue());
									} catch (Exception e) {
										linkMode = o.getCell(1).toString();
									}
									tpv.setLinkMode(linkMode);
								}else{
									msg.append("联系方式不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							case 13:
								String fax;
								if(PropertyUtil.objectNotEmpty(o.getCell(1).toString())){
									try{
										fax = o.getCell(1).getStringCellValue();
									}catch(Exception e){
										fax = o.getCell(1).toString().split("\\.")[0];
									}
									tpv.setFax(fax);
								}else{
									msg.append("传真不能为空！" + "\n");
									resultJson.setSuccess(false);
								}
								break;
							default:
								msg.append("导入异常，建议重新导出模板！" + "\n");
								resultJson.setSuccess(false);
							}
						}

						if (!resultJson.isSuccess()) {
							return;
						}

						// 解析计划名额表
						if (hssfWorkbook.getNumberOfSheets() > 1) {
							sheet = hssfWorkbook.getSheetAt(1);
							ExcelImportResult result = trainingPlanService.divideImportExcelPlanSheet(sheet, applyNum, request);
							if (PropertyUtil.objectNotEmpty(result.getErrorMessage()) && result.getErrorMessage().length() != 0) {
								resultJson.setMsg(result.getErrorMessage().toString());
								resultJson.setSuccess(false);
								return;
							}
							if (result.isResultSign()) {
								String deptName = "";// 报名单位
								Integer cityPlanCount = 0;// 市级计划人数
								Integer countyPlanCount = 0;// 县级计划人数
								sheet = hssfWorkbook.getSheetAt(1);
								Iterator<Row> ite = sheet.rowIterator();
								Integer planNum = 0;
								while (ite.hasNext()) {
									o = ite.next();
									if (o.getRowNum() == 0 || o.getRowNum() == 1 || o.getRowNum() == 2) {
										continue;
									}
									deptName = o.getCell(0).toString();
									String deptId = DeptConstants.PROVINCE_DEPNAME_DEPID_MAPPING.get(deptName);
									cityPlanCount = (int) o.getCell(1).getNumericCellValue();
									countyPlanCount = (int) o.getCell(2).getNumericCellValue();
									planCount = cityPlanCount + countyPlanCount;
									planNum += planCount;

									ClassPlanApplyQueryCommond q = new ClassPlanApplyQueryCommond();
									ClassPlanApplyValidCommond co = null;
									q.setSearchClassId(tpv.getApplyNum());
									q.setSearchDeptCode(deptName);
									List<?> r = classPlanApplyService.findList(q);
									if (PropertyUtil.objectNotEmpty(r)) {
										// update
										co = (ClassPlanApplyValidCommond) r.get(0);
										co.setCityPlanCount(cityPlanCount);
										co.setCountyPlanCount(countyPlanCount);
										co.setPlanCount(planCount);
										classPlanApplyService.update(co);
									} else {
										o.getRowNum();
										co = new ClassPlanApplyValidCommond();
										co.setCityPlanCount(cityPlanCount);
										co.setCountyPlanCount(countyPlanCount);
										co.setPlanCount(planCount);
										co.setDeptId(deptId);
										co.setDeptName(deptName);
										co.setDeptCode(deptName);
										co.setClassId(tpv.getApplyNum());
										classPlanApplyService.save(co);
									}
								}
								tpv.setPlanNum(planNum);
							}
						}
						trainingPlanService.update(tpv);
					} else {
						msg.append("此计划编号不存在，请重新输入编号！" + "\n");
						resultJson.setSuccess(false);
					}
				}
			}
		} catch (IOException e) {
			resultJson.setMsg("模版格式错误，请重新导出模版！");
			resultJson.setSuccess(false);
			e.printStackTrace();
		} finally {
			try {
				if (PropertyUtil.objectNotEmpty(msg) && msg.length() != 0) {
					resultJson.setMsg(msg.toString());
				}
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write(JSONUtils.objToJson(resultJson));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 导入详情名额压缩包
	 * 
	 * @authOr RongSL
	 * */
	/*
	 * @SuppressWarnings({ "unchecked", "unused" }) // @RequestMapping(value =
	 * "/ImportDetailsPlacesForExcel")
	 * 
	 * @RequestMapping(value = "/ImportDetailsPlacesForExcel", method =
	 * RequestMethod.POST)
	 * 
	 * @ResponseBody public void ImportDetailsPlacesForExcel(HttpServletRequest
	 * request, HttpServletResponse response, @ModelAttribute("ResultSate")
	 * ResultState resultState, Model model) { String serverPath =
	 * request.getSession().getServletContext().getRealPath(File.separator); //
	 * 在服务器端创建文件夹 serverPath += System.currentTimeMillis() + File.separator;
	 * ResultJson resultJson = new ResultJson(); resultJson.setMsg("导入成功！");
	 * resultJson.setSuccess(true); StringBuffer msg = new StringBuffer();
	 * InputStream is = null; OutputStream os = null; try {
	 * MultipartHttpServletRequest multipartRequest =
	 * (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap
	 * = multipartRequest.getFileMap(); for (MultipartFile multipartFile :
	 * fileMap.values()) { CommonsMultipartFile commonsMultipartFile =
	 * (CommonsMultipartFile) multipartFile; FileItem item =
	 * commonsMultipartFile.getFileItem(); is = item.getInputStream(); File file
	 * = new File(serverPath); if (!file.exists()) { file.mkdir(); } file = new
	 * File(serverPath, "classInfo.zip"); if (!file.exists()) {
	 * file.createNewFile(); }
	 * 
	 * os = new FileOutputStream(file + File.separator); // is = new
	 * FileInputStream(file); byte[] b = new byte[1024 * 100]; int length = 0;
	 * boolean tag = false; while ((length = is.read(b)) != -1) { os.write(b, 0,
	 * length); } os.close(); is.close();
	 * 
	 * // 判断excel格式和内容是否正确 // file=new File(file+File.separator+item.getName());
	 * is = new FileInputStream(file); // String zipfilename =
	 * "委托部委办班-培训计划详情及名额.zip"; // String dir="Q:\\zip"+File.separator; // File
	 * file = new File(dir+zipfilename);//压缩文件 ZipFile zipFile = new
	 * ZipFile(file);// 实例化ZipFile，每一个zip压缩文件都可以表示为一个ZipFile //
	 * 实例化一个Zip压缩文件的ZipInputStream对象，可以利用该类的getNextEntry()方法依次拿到每一个ZipEntry对象 //
	 * ZipInputStream zipInputStream = new ZipInputStream(new //
	 * FileInputStream(file)); ZipInputStream zipInputStream = new
	 * ZipInputStream(is);
	 * 
	 * ZipEntry zipEntry = null; HSSFWorkbook hssfWorkbook = null; HSSFSheet
	 * sheet = null; TrainingPlanValidCommond tpv = null; String applyNum;//
	 * 计划编号 Integer planCount = 0;// 计划总数 Row o = null; while ((zipEntry =
	 * zipInputStream.getNextEntry()) != null) { String fileName =
	 * zipEntry.getName(); // File temp = new File(file
	 * +File.separator+fileName); // if (! temp.getParentFile().exists()) //
	 * temp.getParentFile().mkdirs(); // os = new FileOutputStream(temp); //
	 * 通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流 is =
	 * zipFile.getInputStream(zipEntry); hssfWorkbook = new HSSFWorkbook(is);
	 * sheet = hssfWorkbook.getSheetAt(0); if (sheet.getPhysicalNumberOfRows()
	 * != 13) { resultJson.setMsg(fileName + "：未使用指定模块，请重新导出！" + "\n");
	 * resultJson.setSuccess(false); } else { tpv = new
	 * TrainingPlanValidCommond(); applyNum =
	 * sheet.getRow(2).getCell(1).toString(); if
	 * (!PropertyUtil.objectNotEmpty(applyNum)) { msg.append(fileName +
	 * "：计划编号不能为空！" + "\n"); resultJson.setSuccess(false); } String
	 * name=sheet.getRow(0).getCell(0).toString(); tpv.setApplyNum(applyNum);
	 * TrainingPlanQueryCommond tpq = new TrainingPlanQueryCommond();
	 * tpq.setSearchApplyNum(applyNum); List<TrainingPlanValidCommond> list =
	 * (List<TrainingPlanValidCommond>) trainingPlanService.findList(tpq); if
	 * (PropertyUtil.objectNotEmpty(list)) { tpv = list.get(0); for (int i = 1;
	 * i < sheet.getPhysicalNumberOfRows(); i++) { o = sheet.getRow(i); switch
	 * (i) { case 1: String className = o.getCell(1).toString();
	 * tpv.setClassName(className); break; case 2: applyNum =
	 * o.getCell(1).toString(); tpv.setApplyNum(applyNum); break; case 3: String
	 * undertakeName = o.getCell(1).toString();
	 * tpv.setUndertakeName(undertakeName); tpq.setDeptName(undertakeName);
	 * String deptId = trainingPlanService.findAdminDeptId(tpq); if
	 * (!PropertyUtil.objectNotEmpty(deptId)) { msg.append(fileName + "中的-" +
	 * undertakeName + "-部门不存在！" + "\n"); resultJson.setSuccess(false); }
	 * tpv.setUndertakeId(deptId); break; case 4: String jointName =
	 * o.getCell(1).toString(); if(PropertyUtil.objectNotEmpty(jointName)){
	 * tpv.setJointName(jointName); tpq.setDeptName(jointName); deptId =
	 * trainingPlanService.findAdminDeptId(tpq); if
	 * (!PropertyUtil.objectNotEmpty(deptId)) { msg.append(fileName + "中的-" +
	 * jointName + "-部门不存在！" + "\n"); resultJson.setSuccess(false); }
	 * tpv.setJointId(deptId); } break; case 5: String planDate =
	 * o.getCell(1).toString(); tpv.setPlanDate(planDate); break; case 6:
	 * Integer planDay = (int) o.getCell(1).getNumericCellValue();
	 * tpv.setPlanDay(planDay); break; case 7: String classObjective =
	 * o.getCell(1).toString(); tpv.setClassObjective(classObjective); break;
	 * case 8: String classValues = o.getCell(1).toString();
	 * tpv.setClassValues(classValues); break; case 9: String trainingObject =
	 * o.getCell(1).toString(); tpv.setTrainingObject(trainingObject); break;
	 * case 10: String trainingAddress = o.getCell(1).toString();
	 * tpv.setTrainingAddress(trainingAddress); break; case 11: String linkMan =
	 * o.getCell(1).toString(); tpv.setLinkMan(linkMan); break; case 12: String
	 * linkMode =o.getCell(1).toString(); tpv.setLinkMode(linkMode); break;
	 * default: msg.append("导入异常，请联系系统管理员！" + "\n");
	 * resultJson.setSuccess(false); } }
	 * 
	 * if (!resultJson.isSuccess()) { return; }
	 * 
	 * // 解析计划名额表 if (hssfWorkbook.getNumberOfSheets() > 1) { sheet =
	 * hssfWorkbook.getSheetAt(1); // ExcelImportResult result =
	 * trainingPlanService.divideImportExcelPlanSheet(sheet, applyNum, request);
	 * // if (result.isResultSign()) { if (true) { String deptName = "";// 报名单位
	 * Integer cityPlanCount = 0;// 市级计划人数 Integer countyPlanCount = 0;// 县级计划人数
	 * sheet = hssfWorkbook.getSheetAt(1); Iterator<Row> ite =
	 * sheet.rowIterator(); Integer planNum = 0; while (ite.hasNext()) { o =
	 * ite.next(); if (o.getRowNum() == 0 || o.getRowNum() == 1 ||o.getRowNum()
	 * == 2) { continue; } deptName = o.getCell(0).toString(); String deptId =
	 * DeptConstants.PROVINCE_DEPNAME_DEPID_MAPPING.get(deptName); cityPlanCount
	 * = (int) o.getCell(1).getNumericCellValue(); countyPlanCount = (int)
	 * o.getCell(2).getNumericCellValue(); planCount = cityPlanCount +
	 * countyPlanCount; planNum += planCount;
	 * 
	 * ClassPlanApplyQueryCommond q = new ClassPlanApplyQueryCommond();
	 * ClassPlanApplyValidCommond co = null;
	 * q.setSearchClassId(tpv.getApplyNum()); q.setSearchDeptCode(deptName);
	 * List<?> r = classPlanApplyService.findList(q); if
	 * (PropertyUtil.objectNotEmpty(r)) { // update co =
	 * (ClassPlanApplyValidCommond) r.get(0);
	 * co.setCityPlanCount(cityPlanCount);
	 * co.setCountyPlanCount(countyPlanCount); co.setPlanCount(planCount);
	 * classPlanApplyService.update(co); } else { o.getRowNum(); co = new
	 * ClassPlanApplyValidCommond(); co.setCityPlanCount(cityPlanCount);
	 * co.setCountyPlanCount(countyPlanCount); co.setPlanCount(planCount);
	 * co.setDeptId(deptId); co.setDeptName(deptName); co.setDeptCode(deptName);
	 * co.setClassId(tpv.getApplyNum()); classPlanApplyService.save(co); }
	 * System.out.println(deptName + "--" + cityPlanCount + "--" +
	 * countyPlanCount); } tpv.setPlanNum(planNum);
	 * trainingPlanService.update(tpv); } } // 保存到本地 // int len = 0; // while
	 * ((len = is.read()) != -1) // os.write(len); // os.close(); is.close(); }
	 * else { msg.append(fileName + "：此计划编号不存在，请重新输入编号！" + "\n");
	 * resultJson.setSuccess(false); } } } zipInputStream.close(); is.close();
	 * // zipFile.close(); } } catch (Exception e) { e.printStackTrace();
	 * msg.append("压缩包格式错误，请导入标准压缩包！"); resultJson.setSuccess(false); try {
	 * is.close(); } catch (IOException e1) { e1.printStackTrace(); } } finally
	 * { response.setContentType("text/html;charset=UTF-8"); PrintWriter out =
	 * null; try { out = response.getWriter();
	 * if(PropertyUtil.objectNotEmpty(msg.toString())){
	 * resultJson.setMsg(msg.toString()); }
	 * out.write(JSONUtils.objToJson(resultJson)); } catch (Exception e) {
	 * e.printStackTrace(); } out.flush(); out.close(); // 删除生成文件夹，Excel及ZIP
	 * ZipUtil.deleteExcelPath(new File(serverPath)); } }
	 */

	/**
	 * 导入名额
	 * 
	 * @authOr RongSL
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	// @RequestMapping(value = "/ImportPlacesForExcel")
	@RequestMapping(value = "/ImportPlacesForExcel", method = RequestMethod.POST)
	@ResponseBody
	public void ImportPlacesForExcel(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("ResultSate") ResultState resultState, Model model) {
		ResultJson resultJson = new ResultJson();
		ClassPlanApplyValidCommond commond;
		List<ClassPlanApplyValidCommond> list = new ArrayList<ClassPlanApplyValidCommond>();
		// String path = "d://计划名额模板.xls";
		// File f = new File(path);
		HSSFWorkbook hssfWorkbook = null;
		HSSFSheet sheet = null;
		HSSFRow row = null;
		HSSFCell cell = null;
		String applyNum = null;// 计划编号
		String deptName = null;// 报名单位
		Integer cityPlanCount = 0;// 市级计划人数
		Integer countyPlanCount = 0;// 县级计划人数
		Integer planCount = 0;// 计划总数
		Row o = null;
		InputStream is = null;
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (MultipartFile multipartFile : fileMap.values()) {
			CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
			FileItem item = commonsMultipartFile.getFileItem();
			try {
				is = item.getInputStream();
				// 判断excel格式和内容是否正确
				// is = new FileInputStream(f);
				ExcelImportResult result = trainingPlanService.divideImportExcelPlan(is, request);
				if (result.isResultSign()) {
					is = item.getInputStream();
					hssfWorkbook = new HSSFWorkbook(is);
					// Workbook wb = ExcelUtil.createWorkbook(is);
					for (int i = 0; i < hssfWorkbook.getNumberOfSheets(); i++) {
						sheet = hssfWorkbook.getSheetAt(i);
						row = sheet.getRow(0);
						cell = row.getCell(1);
						applyNum = cell.toString().trim();
						Iterator<Row> ite = sheet.rowIterator();
						while (ite.hasNext()) {
							o = ite.next();
							if (o.getRowNum() == 0 || o.getRowNum() == 1 || o.getRowNum() == 2) {
								continue;
							}
							commond = new ClassPlanApplyValidCommond();
							deptName = o.getCell(0).toString();
							String deptId = DeptConstants.PROVINCE_DEPNAME_DEPID_MAPPING.get(deptName);
							cityPlanCount = (int) o.getCell(1).getNumericCellValue();
							countyPlanCount = (int) o.getCell(2).getNumericCellValue();
							planCount = cityPlanCount + countyPlanCount;
							commond.setCityPlanCount(PropertyUtil.objectNotEmpty(cityPlanCount) ? cityPlanCount : 0);
							commond.setCountyPlanCount(countyPlanCount);
							commond.setPlanCount(planCount);
							commond.setClassId(applyNum);
							commond.setDeptId(deptId);
							commond.setDeptName(deptName);
							commond.setDeptCode(deptName);
							list.add(commond);
						}
						
						Integer planNum = 0;// 总人数
						// save
						for (ClassPlanApplyValidCommond com : list) {
							// 查询是否已经初始化过计划报名
							ClassPlanApplyQueryCommond queryCommond = new ClassPlanApplyQueryCommond();
							queryCommond.setSearchClassId(com.getClassId());
							queryCommond.setSearchDeptName(com.getDeptName());
							List<?> resultList = classPlanApplyService.findList(queryCommond);
							planNum += com.getCityPlanCount() + com.getCountyPlanCount();
							if (PropertyUtil.objectNotEmpty(resultList)) {
								// update
								ClassPlanApplyValidCommond co = (ClassPlanApplyValidCommond) resultList.get(0);
								co.setCityPlanCount(com.getCityPlanCount());
								co.setCountyPlanCount(com.getCountyPlanCount());
								co.setPlanCount(com.getPlanCount());
								classPlanApplyService.update(co);
							} else {
								// save
								com.setPlanCount(com.getCityPlanCount() + com.getCountyPlanCount());
								classPlanApplyService.save(com);
							}
						}
						TrainingPlanQueryCommond query = new TrainingPlanQueryCommond();
						query.setSearchApplyNum(applyNum);
						query.setSearchPlanNum(planNum);
						trainingPlanService.updatePlanNum(query);
					}
					resultJson.setMsg("导入成功！");
					resultJson.setSuccess(true);
				} else {
					resultJson.setMsg(result.getErrorMessage().toString());
					resultJson.setSuccess(true);
				}
				response.setContentType("text/html;charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.write(JSONUtils.objToJson(resultJson));
				out.flush();
				out.close();
				// response.setCharacterEncoding("UTF-8");
				// response.getOutputStream().write(((JSONUtils.objToJson(resultJson)).getBytes("UTF-8")));
				// response.getOutputStream().print(JSONUtils.objToJson(resultJson));
			} catch (Exception e) {
				e.printStackTrace();
				resultState.setMessage("导入失败，请联系管理员！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 查看驳回原因
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/lookRejectReason")
	public void lookRejectReason(@ModelAttribute("result") TrainingPlanValidCommond vCommond, @ModelAttribute("ResultSate") ResultState resultState) {
		try {
			vCommond = trainingPlanService.findTrainingPlan(vCommond);
			resultState.setMessage("查询成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		} catch (Exception e) {
			System.out.println("查看驳回原因出错！");
			resultState.setMessage("查询失败，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 发布培训计划
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/publishTrainingPlan")
	public void publishTrainingPlan(TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState, HttpServletRequest request) {
		try {
			// queryCommond.setSearchPublishState(1);
			// trainingPlanService.updatePlanState(queryCommond);
			Date d = new Date();
			for (String id : queryCommond.getSearchPlanIds()) {
				// 更新培训计划状态及发布时间
				TrainingPlanValidCommond tpv = new TrainingPlanValidCommond();
				tpv.setPlanId(id);
				tpv = trainingPlanService.findTrainingPlan(tpv);
				tpv.setPublishDate(d);
				tpv.setPublishState(TrainingPlan.PUBLISHSTATE_Y);

				TrainingClassValidCommond vCommond = new TrainingClassValidCommond();
				if (PropertyUtil.objectNotEmpty(queryCommond.getCoursesNum())) {
					vCommond.setClassNum(queryCommond.getCoursesNum());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getClassName())) {
					vCommond.setClassName(tpv.getClassName());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getUndertakeName())) {
					vCommond.setMinistrieName(tpv.getUndertakeName());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getJointName())) {
					vCommond.setJointMinistrieName(tpv.getJointName());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getUndertakeId())) {
					vCommond.setMinistrieID(tpv.getUndertakeId());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getJointId())) {
					vCommond.setJointMinistrieID(tpv.getJointId());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getPlanDay())) {
					vCommond.setTrainingHour(Double.valueOf(tpv.getPlanDay()));
				}
				if (PropertyUtil.objectNotEmpty(tpv.getTrainingAddress())) {
					vCommond.setTrainingAddress(tpv.getTrainingAddress());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getTrainingObject())) {
					vCommond.setClassDescription(tpv.getTrainingObject());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getPlanNum())) {
					vCommond.setClassUserNum(tpv.getPlanNum());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getStartPlanDateStr())) {
					vCommond.setExpectTime(tpv.getStartPlanDateStr());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getLinkMan())) {
					vCommond.setContactPeople(tpv.getLinkMan());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getLinkMode())) {
					vCommond.setContactTel(tpv.getLinkMode());
				}
				if (PropertyUtil.objectNotEmpty(tpv.getFax())) {
					vCommond.setFax(tpv.getFax());
				}

				// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				// if(PropertyUtil.objectNotEmpty(vCommond.getBeginDateStr())){
				// String beginDateStr=vCommond.getBeginDateStr();
				// vCommond.setBeginDate(sdf.parse(beginDateStr));
				// }
				// if(PropertyUtil.objectNotEmpty(vCommond.getEndDateStr())){
				// String endDateStr=vCommond.getEndDateStr();
				// vCommond.setEndDate(sdf.parse(endDateStr));
				// // 评估开始结束时间为结班时间的前1天后2天 add by LongJZ at 2016-3-30
				// vCommond.setAssessStartTime(addDay(endDateStr, -1));
				// vCommond.setAssessEndTime(addDay(endDateStr, 2));
				// }
				// if(PropertyUtil.objectNotEmpty(vCommond.getEnterBeginTimeStr())){m
				// String enterBeginTimeStr=vCommond.getEnterBeginTimeStr();
				// vCommond.setEnterBeginTime(sdf.parse(enterBeginTimeStr));
				// }
				// if(PropertyUtil.objectNotEmpty(vCommond.getEnterEndTimeStr())){
				// String enterEndTimeStr=vCommond.getEnterEndTimeStr();
				// vCommond.setEnterEndTime(sdf.parse(enterEndTimeStr));
				// }
				// 配置培训班的数据字典的属性
				// tclass=configureBaseData(tclass,vCommond);
				// 开班结班状态判断
				// vCommond=decideOpenState(vCommond);
				/*
				 * vCommond.setTrainingHour(0.0);//学时
				 * vCommond.setClassUserNum(0);//班级人数
				 */
				vCommond.setPublishState(TrainingClass.IS_PUBLISH_N);
				vCommond.setActiveState(TrainingClass.IS_ACTIVE_Y);
				vCommond.setAuditState(TrainingClass.IS_N_AUDIT);// 未审核
				vCommond.setReportState(TrainingClass.IS_REPORT_N);// 未上报
				vCommond.setOpenState(TrainingClass.IS_OPENSTATE_N);// 只要是未发布，无论填写的开始结束时间是什么班级状态都是是未开班
				vCommond.setSignUpState(TrainingClass.IS_SIGNUP_N);// //只要是未发布，无论填写的报名开始结束时间是什么报名状态都是是未开始报名
				vCommond.setPerfectState(TrainingClass.PERFECTSTATE_N);// 信息未完善
				vCommond.setAllotDeptState(TrainingClass.IS_ALLOTDEPT_N);// 未分配指定单位状态

				/*
				 * 1.判断编号是否重复（整个系统判重）
				 */
				if (vCommond.getClassNum().length() != 7) {
					resultState.setState(ResultState.RESULT_STATE_FAIL);
					resultState.setMessage("编号长度必须为7位数字或字母,请重新输入！");
					return;
				}
				boolean suc = trainingClassService.decideClassNum(vCommond);
				if (suc) {
					resultState.setState(ResultState.RESULT_STATE_FAIL);
					resultState.setMessage("编号重复,请重新输入！");
					return;
				}
				/*
				 * 2.判断名称是否重复（不同承办部委下可以重复）
				 */
				boolean succ = trainingClassService.decideClassName(vCommond);
				if (succ) {
					resultState.setState(ResultState.RESULT_STATE_FAIL);
					resultState.setMessage("此培训计划已完成发布！");
					return;
				}

				// if(token.isTokenValid(request, true)){//判断token
				// TrainingClass tclass= (TrainingClass) vCommond.toEntity();
				// 拼凑时间
				// if (PropertyUtil.objectNotEmpty(vCommond.getBeginDateStr()))
				// {
				// tclass.setBeginDate(DateUtil.getDateByString(vCommond.getBeginDateStr(),
				// "yyyy-MM-dd"));
				// }
				// if (PropertyUtil.objectNotEmpty(vCommond.getEndDateStr())) {
				// tclass.setEndDate(DateUtil.getDateByString(vCommond.getEndDateStr(),
				// "yyyy-MM-dd"));
				// }

				trainingClassService.save(vCommond);

				// 新增培训计划名额
				// trainingPlanService.updatePlanApply(tp.getApplyNum(),vCommond.getClassId());
				ClassPlanApplyQueryCommond query = new ClassPlanApplyQueryCommond();
				query.setSearchClassId(tpv.getApplyNum());
				List<ClassPlanApplyQueryBean> resultList = trainingPlanService.findClassPlanApplyQueryBeanList(query);
				ClassPlanApplyValidCommond cp = null;
				for (ClassPlanApplyQueryBean c : resultList) {
					cp = new ClassPlanApplyValidCommond();
					BeanUtils.copyProperties(c, cp);
					cp.setAsignCityCount(cp.getCityPlanCount());
					cp.setAsignCountyCount(cp.getCountyPlanCount());
					cp.setAsignCount(cp.getPlanCount());
					cp.setDeptName(c.getDeptCode());
					cp.setClassId(vCommond.getClassId());
					classPlanApplyService.save(cp);
				}
				
//				/**
//				 *新增企业			//垃圾代码
//				 *@author RongSL
//				 * @date 2016-11-16
//				 * */
//				String dName = "企业";
//				String deptId = DeptConstants.PROVINCE_DEPNAME_DEPID_MAPPING.get(dName);
//				cp = new ClassPlanApplyValidCommond();
//				cp.setAsignCityCount(0);
//				cp.setPlanCount(0);
//				cp.setCityPlanCount(0);
//				cp.setCountyPlanCount(0);
//				cp.setAsignCountyCount(0);
//				cp.setAsignCount(0);
//				cp.setDeptId(deptId);
//				cp.setDeptName(dName);
//				cp.setDeptCode(dName);
//				cp.setClassId(vCommond.getClassId());
//				classPlanApplyService.save(cp);

				// 更新计划发布状态
				trainingPlanService.update(tpv);

				resultState.setMessage("发布成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);

				try {
					/**
					 * 添加提醒
					 * @Date 2016-05-12
					 * @author RongSL
					 * @Params 提醒类型，培训班名称，承办部委名称，提醒分类
					 * */
					// 给部委发送提醒
					remindService.remindOperate(Remind.FBPXJH, vCommond.getMinistrieName(), vCommond.getClassName(), RoleConstants.ROLE_BW_NAME, vCommond.getClassId(), Remind.PXJH);
					// 给地方管理员发送提醒
					String deptIds[] = trainingPlanService.findDeptId(tpv);
					if(PropertyUtil.objectNotEmpty(deptIds)){
						for (String did : deptIds) {
							String deptName = DeptConstants.PROVINCE_SHORT_DEPNAME_MAPPING.get(DeptConstants.PROVINCE_SHORT_DEPID_MAPPING_RESVERSE.get(did));
							remindService.remindOperate(Remind.FBPXJH, deptName, vCommond.getClassName(), RoleConstants.ROLE_DF_NAME, vCommond.getClassId(), Remind.PXJH);
						}
					}
				} catch (Exception e) {
					System.out.println("新增培训班提醒接口出错了！");
				}
			}
			// }
		} catch (Exception e) {
			resultState.setMessage("发布失败！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 下发计划到地方管理员
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/planLssuedAdd")
	public void planLssuedAdd(TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		try {
			if (PropertyUtil.objectNotEmpty(queryCommond.getDeptIds()) && PropertyUtil.objectNotEmpty(queryCommond.getSearchPlanIds())) {
				for (String s : queryCommond.getSearchPlanIds()) {
					queryCommond.setSearchPlanId(s);
					trainingPlanService.planIssuedAdd(queryCommond);
					TrainingPlanValidCommond tp = new TrainingPlanValidCommond();
					tp.setPlanId(queryCommond.getSearchPlanId());
					tp = trainingPlanService.findTrainingPlan(tp);
					tp.setIssuedState(TrainingPlan.ISSUEDSTATE_Y);
					// 更新下发状态
					trainingPlanService.update(tp);
					for (String did : queryCommond.getDeptIds()) {
						String deptName = DeptConstants.PROVINCE_SHORT_DEPID_MAPPING_RESVERSE.get(did);
						deptName = DeptConstants.PROVINCE_SHORT_DEPNAME_MAPPING.get(deptName);
						try {
							/**
							 * 添加提醒
							 * 
							 * @Date 2016-05-12
							 * @author RongSL
							 * @Params 提醒类型，培训班名称，承办部委名称，提醒分类
							 * */
							remindService.remindOperate(Remind.XFPXJH, tp.getClassName(), deptName, tp.getPlanId(), Remind.PXB);
						} catch (Exception e) {
							System.out.println("培训计划下发提醒接口出错了！");
						}
					}
				}
				resultState.setMessage("操作成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			} else {
				resultState.setMessage("请至少选择一个下发单位！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("下发培训计划出错！");
			resultState.setMessage("操作失败，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 查看培训计划列表
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/findPlanList")
	public void findPlanList(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, HttpServletRequest request, @ModelAttribute("resultState") ResultState resultState) {
		try {
			Role role = (Role) request.getSession().getAttribute("currentRole");
			List<TrainingPlanValidCommond> list = null;
			Department dep = (Department) request.getSession().getAttribute("currentScope");
			if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_BW_ADMIN)) {
				// 部委管理员列表
				Department d = (Department) request.getSession().getAttribute("currentScope");
				if (!d.getDeptID().equals(1 + "")) {
					queryCommond.setSearchUndertakeID(dep.getDeptID());
				}
				list = trainingPlanService.findPlanListBW(queryCommond);
			} else if (role.getRoleCode().equals(RoleConstants.ROLE_CODE_ZZB_ADMIN)) {
				// 中组部管理员列表
				// if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchAuditState())){
				// queryCommond.setSearchAuditState(TrainingPlan.AUDITSTATE_W);
				// }
				list = trainingPlanService.findPlanList(queryCommond);
			} else {
				// 地方管理员列表
				queryCommond.setSearchDeptId(dep.getDeptID());
				list = trainingPlanService.findPlanListDF(queryCommond);
			}
			for (TrainingPlanValidCommond t : list) {
				if (PropertyUtil.objectNotEmpty(t.getRejectReason())) {
					String r = t.getRejectReason();
					r = URLEncoder.encode(r, "UTF-8").replaceAll("\\+", "%20");
					t.setRejectReason(r);
				}
			}
			queryCommond.setResultList(list);
			resultState.setMessage("查询成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			resultState.setMessage("查询失败！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 查看已下发单位
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/lookIssuedList")
	public void lookIssuedList(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		try {
			List<TrainingPlanValidCommond> list = trainingPlanService.lookIssuedList(queryCommond);
			queryCommond.setResultList(list);
			resultState.setMessage("查询成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			resultState.setMessage("查询失败！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 下发单位列表
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/findIssuedList")
	public void findIssuedList(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		try {
			// queryCommond.setSearchSelectState(2);
			List<TrainingPlanValidCommond> list = trainingPlanService.findIssuedList(queryCommond);
			queryCommond.setResultList(list);
			resultState.setMessage("查询成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			resultState.setMessage("查询失败！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	/**
	 * 查看反馈意见列表
	 * 
	 * @Date 2016-07-25
	 * @author RongSL
	 * */
	@RequestMapping("/findFeedbackList")
	public void findFeedbackList(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		try {
			List<TrainingPlanValidCommond> list = trainingPlanService.findFeedbackList(queryCommond);
			queryCommond.setResultList(list);
			resultState.setMessage("查询成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			resultState.setMessage("查询失败！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

	public Date addDay(String date, int days) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cd = Calendar.getInstance();
		cd.setTime(sdf.parse(date));
		cd.add(Calendar.DATE, days);// 增加一天
		return cd.getTime();
	}

//	public void sort(List<ClassPlanApplyQueryBean> data) {
//		Collections.sort(data, new Comparator<ClassPlanApplyQueryBean>() {
//			public int compare(ClassPlanApplyQueryBean o1, ClassPlanApplyQueryBean o2) {
//				String d1 = o1.getDeptId();
//				String d2 = o2.getDeptId();
//				// 升序
//				return d1.compareTo(d2);
//				// 降序
//				// return b.compareTo(a);
//			}
//		});
//	}

	public void getClassNum(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState) {
		// String
		// classNum="select max(b.class_num) from training_class b where b.class_num like '2016%' "
	}

	/**
	 * 自动获取培训班编号
	 * 
	 * @author zyg
	 * @CreateDate 2016-09-18
	 */
	@RequestMapping("/autoClassNum")
	public String getAutoClassNum(@ModelAttribute("result") TrainingClassValidCommond valid, TrainingPlanQueryCommond queryCommond, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("ResultSate") ResultState resultState) {
		try {
			if (PropertyUtil.objectNotEmpty(queryCommond.getSearchPlanId())) {
				TrainingPlanValidCommond tp = new TrainingPlanValidCommond();
				tp.setPlanId(queryCommond.getSearchPlanId());
				tp = trainingPlanService.findTrainingPlan(tp);
				String year = tp.getStartPlanDateStr().split("-")[0];
				String classNum = trainingPlanService.getMaxClassNum(year);
				classNum = year + StringUtil.CompleteNum(Integer.valueOf(classNum.substring(4)) + 1, 3);
				valid.setClassNum(classNum);
				resultState.setMessage("操作成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("自动获取培训班编号出错！");
			resultState.setMessage("操作失败，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}

	/**
	 * 查询所有培训班计划名额
	 * 
	 * @Date 2016-09-20
	 * @author ZhouYG
	 * */
	@RequestMapping("/lookAllPlanPlaces")
	public void lookAllPlanPlaces(@ModelAttribute("resultList") TrainingPlanQueryCommond queryCommond, @ModelAttribute("resultState") ResultState resultState, HttpServletRequest request) {
		try {
			List<ClassPlanApplyQueryBean> resultList1 = null;// 对比集合
			List<TrainingPlanApplyContrast> l = null;
			Department dep = (Department) request.getSession().getAttribute("currentScope");
			queryCommond.setSearchDeptId(dep.getDeptID());
			resultList1 = trainingPlanService.findClassPlanApplyList(queryCommond);
			l = trainingPlanService.classPlanApplyQueryBeanToTrainingPlanApplyContrast(resultList1, null);
			if(PropertyUtil.objectNotEmpty(queryCommond.getSearchApplyNums())&&queryCommond.getSearchApplyNums().length==1){
				l.remove(0);
			}
			queryCommond.setResultList(l);
			resultState.setMessage("查询成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);

		} catch (Exception e) {
			e.printStackTrace();
			resultState.setMessage("缺少参数，请重试！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
	}

}